package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasFormSubDataEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.constant.EsNormalConstant;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.model.PaasFormSubDataEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.pojo.dto.SearchDataInConditionDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.TopHitsDTO;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.ComboTypeEnum;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.help.PaasFormHelp;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.field.LinkFormPoJo;
import com.xbongbong.paas.field.LinkInfoPojo;
import com.xbongbong.paas.field.RelyConditionPoJo;
import com.xbongbong.paas.field.RelyPoJo;
import com.xbongbong.paas.field.SubRelyFieldPojo;
import com.xbongbong.saas.enums.SearchDataFromEnum;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.help.UserHelp;
import com.xbongbong.paas.help.service.impl.FormDataLinkDataUpdateGetServiceImpl;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.ItemDataPoJo;
import com.xbongbong.paas.pojo.dto.DepartmentListDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateGetDTO;
import com.xbongbong.paas.pojo.dto.ParseSingleRowDataDTO;
import com.xbongbong.paas.pojo.dto.SearchInConditionDTO;
import com.xbongbong.paas.pojo.dto.UserAndDepartmentGetDTO;
import com.xbongbong.paas.pojo.vo.DepartmentListVO;
import com.xbongbong.paas.pojo.vo.LinkResultDataVO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.pojo.vo.ParseSingleRowDataVO;
import com.xbongbong.paas.pojo.vo.SearchDataInConditionVO;
import com.xbongbong.paas.pojo.vo.UserAndDepartmentGetVO;
import com.xbongbong.paas.service.DepartmentService;
import com.xbongbong.paas.service.DistinctDataService;
import com.xbongbong.paas.service.impl.base.BaseFormDataService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.thread.TransmittableThreadLocalUtil;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.ItemUtil;
import com.xbongbong.paas.util.ParentBusinessConditionUtil;
import com.xbongbong.parent.condition.ProConditionHelp;
import com.xbongbong.parent.parse.data.FormDataUpdateGetAnalysisDataHelp;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.domain.entity.LabelEntity;
import com.xbongbong.pro.enums.PaasStageEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.packages.enums.FeaturesEnum;
import com.xbongbong.paas.field.LinkListPojo;
import com.xbongbong.pro.formexplain.pojo.ConditionExplainPojo;
import com.xbongbong.pro.formexplain.pojo.DefaultLinkInfoPojo;
import com.xbongbong.pro.label.pojo.LabelPojo;
import com.xbongbong.pro.service.toolbox.statistic.help.ChartQueryHelp;
import com.xbongbong.pro.statistic.model.DataSetModel;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StockConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.PublicGroupSeniorEntity;
import com.xbongbong.saas.domain.entity.WarehouseUserEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.domain.entity.WorkOrderStageEntity;
import com.xbongbong.saas.domain.entity.WorkOrderTemplateEntity;
import com.xbongbong.saas.enums.BirthdayFilterEnum;
import com.xbongbong.saas.enums.ListGroupEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.WorkOrderNodeStatusEnum;
import com.xbongbong.saas.enums.WorkOrderStatusEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.BatchFlowBillEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.DistributorAccountEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.ProductSerialBalanceEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.StockFlowBillEnum;
import com.xbongbong.saas.enums.business.StockStandingBookEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.help.FormDataAnalysisHelp;
import com.xbongbong.saas.help.SaasFormHelp;
import com.xbongbong.saas.help.SaasListHelp;
import com.xbongbong.saas.model.LabelModel;
import com.xbongbong.saas.model.SpecificationModel;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.saas.model.impl.IndexTypeModelImpl;
import com.xbongbong.saas.model.impl.PublicGroupSeniorModelImpl;
import com.xbongbong.saas.service.ScoreRangeService;
import com.xbongbong.saas.service.WarehouseService;
import com.xbongbong.saas.service.WorkOrderTemplateService;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.util.AddressUtil;
import com.xbongbong.workorder.service.WorkOrderStageService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.IndexBoost;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.existsQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author: wufeng
 * @date: 2018/10/29 11:22
 * @desrcption: 获取去重的数据
 */
@Service("distinctData")
public class DistinctDataServiceImpl implements DistinctDataService {

    private static final Logger LOG = LoggerFactory.getLogger(DistinctDataServiceImpl.class);

    private static final String UNDERLINE = "_";

    @Resource
    private EsHelper esHelper;
    @Resource
    private UserHelp userHelp;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private WorkOrderTemplateService workOrderTemplateService;
    @Resource
    private WorkOrderStageService workOrderStageService;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private FormDataUpdateGetAnalysisDataHelp formDataUpdateGetAnalysisDataHelp;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private SaasListHelp saasListHelp;
    @Resource
    private BaseFormDataService baseFormDataService;
    @Resource
    private ProConditionHelp proConditionHelp;
    @Resource
    private WarehouseService warehouseService;
    @Resource
    private UserModel userModel;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private SpecificationModel specificationModel;
    @Resource
    private FormDataAnalysisHelp formDataAnalysisHelp;
    @Resource
    private FormDataLinkDataUpdateGetServiceImpl formDataLinkDataUpdateGetService;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private LabelModel labelModel;
    @Resource
    private PaasFormSubDataEsModel paasFormSubDataEsModel;
    @Resource
    private ScoreRangeService scoreRangeService;
    @Resource
    private SaasFormHelp saasFormHelp;
    @Resource
    private PaasFormHelp paasFormHelp;
    @Resource
    private ChartQueryHelp chartQueryHelp;
    @Resource
    private IndexTypeModelImpl indexTypeModel;
    @Resource
    private PublicGroupSeniorModelImpl publicGroupSeniorModel;
    @Resource
    private DataSetModel dataSetModel;

    @Override
    public SearchDataInConditionVO listOfLinkForm(SearchDataInConditionDTO searchDataInConditionDTO) throws XbbException{
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        try {
            String corpid = searchDataInConditionDTO.getCorpid();
            List<String> featureList = packageHelp.getFeatureList(corpid);
            if (!featureList.contains(FeaturesEnum.LINKFORM.getAlias())) {
                searchDataInConditionVO.setItems(new ArrayList<>());
                searchDataInConditionVO.setDepartmentList(new JSONArray());
                return searchDataInConditionVO;
            }
            LinkFormPoJo linkFormPoJo = searchDataInConditionDTO.getLinkForm();
            // 获取联动表单的字段信息
            PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(searchDataInConditionDTO.getCorpid(), linkFormPoJo.getSourceFormId(), linkFormPoJo.getSourceBusinessType());

            List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            if (Objects.equals(linkFormPoJo.getSourceBusinessType(), XbbRefTypeEnum.PRODUCT.getCode())) {
                List<ItemPoJo> productItems = saasFormHelp.getProductItems(corpid);
                for (FieldAttrEntity fieldAttrEntity : explainList) {
                    if (Objects.equals(fieldAttrEntity.getSaasAttr(), ProductEnum.UNIT.getSaasAttr())) {
                        fieldAttrEntity.setItems(productItems);
                        break;
                    }
                }
                paasFormExplainEntity.setExplains(JSON.toJSONString(explainList));
            }
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), linkFormPoJo.getDisplayField());


            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            //解析查询条件
            boolQueryBuilder.filter(termQuery("corpid.keyword", searchDataInConditionDTO.getCorpid()));
            boolQueryBuilder.filter(termQuery("appId", linkFormPoJo.getSourceAppId()));
            boolQueryBuilder.filter(termQuery("formId", linkFormPoJo.getSourceFormId()));
            boolQueryBuilder.filter(termQuery("del", searchDataInConditionDTO.getDel()));

            // 获取权限内的数据
            searchDataInConditionDTO.setDefaultGroup(1);
            searchDataInConditionDTO.setListGroupId(ListGroupEnum.ALL.getCode().longValue());
            searchDataInConditionDTO.setSaasMark(linkFormPoJo.getSourceSaasMark());
            searchDataInConditionDTO.setBusinessType(linkFormPoJo.getSourceBusinessType());
            searchDataInConditionDTO.setSubBusinessType(linkFormPoJo.getSourceBusinessType());
            searchDataInConditionDTO.setFormId(linkFormPoJo.getSourceFormId());

            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, linkFormPoJo.getSourceBusinessType(), linkFormPoJo.getSourceSaasMark());
            EsUtil.parseCondition(boolQueryBuilder,searchDataInConditionDTO.getConditionsList(),"",searchDataInConditionDTO.getCorpid(),searchDataInConditionDTO.getBusinessType());
            BoolQueryBuilder boolQuery = boolQuery();
            EsUtil.parseShouldCondition(boolQuery,searchDataInConditionDTO.getShouldConditionsList(),"",searchDataInConditionDTO.getCorpid(),searchDataInConditionDTO.getBusinessType());
            boolQueryBuilder.filter(boolQuery);
            // 共享权限
            EsUtil.parseSharePermissionCondition(boolQueryBuilder, searchDataInConditionDTO.getSharePermission(), searchDataInConditionDTO.getCorpid(), searchDataInConditionDTO.getBusinessType(), false);
            // 产品只需要父产品即可
            productCondition(boolQueryBuilder,linkFormPoJo.getSourceBusinessType(), linkFormPoJo.getSourceBusinessType(), "");
            // 根据需要显示的字段去获取es前缀
            FieldAttrEntity sourceField = explainMap.get(linkFormPoJo.getDisplayField());
            if(sourceField == null){
                searchDataInConditionVO.setItems(new ArrayList<>());
                searchDataInConditionVO.setDepartmentList(new JSONArray());
                return searchDataInConditionVO;
            }
            // 模糊查询 类似于sql中的like
            likeBoolQuery(searchDataInConditionDTO.getValue(), sourceField, corpid,
                    linkFormPoJo.getSourceFormId(), linkFormPoJo.getSourceBusinessType(), linkFormPoJo.getSourceSaasMark(), boolQueryBuilder);

            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
            NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();

            FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(sourceField.getFieldType());
            TopHitsDTO topHitsDTO = new TopHitsDTO();
            BeanUtil.copyProperties(searchDataInConditionDTO, topHitsDTO);
            topHitsDTO.setSearchQuery(searchQuery);
            topHitsDTO.setField("data."+linkFormPoJo.getDisplayField());
            //阶段推进器需要阶段流程id定位数据版本
            if (Objects.equals(sourceField.getFieldType(), FieldTypeEnum.STAGE_THRUSTER.getType())) {
                List<String> source = new ArrayList<>();
                source.add("data." + linkFormPoJo.getDisplayField());
                source.add("data." + PaasStageEnum.STAGE_PROCESS_ID.getAttr());
                topHitsDTO.setSource(source);
            }
            topHitsDTO.setFieldTypeEnum(fieldTypeEnum);
            topHitsDTO.setSaasMark(linkFormPoJo.getSourceSaasMark());
            topHitsDTO.setBusinessType(linkFormPoJo.getSourceBusinessType());

            List<PaasFormDataEntityExt> dataList = esHelper.topHits(topHitsDTO, indexTypeEnum);
            if (dataList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
            BeanUtil.copyProperties(searchDataInConditionDTO, userAndDepartmentGetDTO);
            userAndDepartmentGetDTO.setExplainList(explainList);
            // TODO getItemDataList新增了最后一个参数，目前传null，需要确认 by HU
            List<ItemDataPoJo> list = getItemDataList(userAndDepartmentGetDTO, dataList, sourceField,
                    linkFormPoJo.getSourceSaasMark(), linkFormPoJo.getSourceBusinessType(), linkFormPoJo.getSourceFormId(), null);
            searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("distinctData关联其他表单检索数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return searchDataInConditionVO;
    }


    @Override
    public SearchDataInConditionVO listOfRely(SearchDataInConditionDTO searchDataInConditionDTO) throws XbbException {
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        try {
            String corpid = searchDataInConditionDTO.getCorpid();
            RelyPoJo relyPoJo = searchDataInConditionDTO.getRely();
            if (Objects.isNull(relyPoJo)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
            PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(corpid, relyPoJo.getSourceFormId(), relyPoJo.getSourceBusinessType());
            List<FieldAttrEntity> explainList = JSON.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);

            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), relyPoJo.getLinkField());
            FieldAttrEntity linkFieldAttr = explainMap.get(relyPoJo.getLinkField());
            if(linkFieldAttr == null) {
                searchDataInConditionVO.setItems(new ArrayList<>());
                searchDataInConditionVO.setDepartmentList(new JSONArray());
                return searchDataInConditionVO;
            }
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            //解析查询条件
            boolQueryBuilder.filter(termQuery("corpid.keyword", searchDataInConditionDTO.getCorpid()));
            boolQueryBuilder.filter(termQuery("appId", relyPoJo.getSourceAppId()));
            boolQueryBuilder.filter(termQuery("formId", relyPoJo.getSourceFormId()));
            boolQueryBuilder.filter(termQuery("del", searchDataInConditionDTO.getDel()));
            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, relyPoJo.getSourceBusinessType(), relyPoJo.getSourceSaasMark());
            EsUtil.parseCondition(boolQueryBuilder,searchDataInConditionDTO.getConditionsList(),"",searchDataInConditionDTO.getCorpid(),searchDataInConditionDTO.getBusinessType());
            EsUtil.parseShouldCondition(boolQueryBuilder,searchDataInConditionDTO.getShouldConditionsList(),"",searchDataInConditionDTO.getCorpid(),searchDataInConditionDTO.getBusinessType());
            // 共享权限
            EsUtil.parseSharePermissionCondition(boolQueryBuilder, searchDataInConditionDTO.getSharePermission(), searchDataInConditionDTO.getCorpid(), searchDataInConditionDTO.getBusinessType(), false);
            productCondition(boolQueryBuilder,relyPoJo.getSourceBusinessType(), relyPoJo.getSourceBusinessType(), "");
            String attr = relyPoJo.getLinkField();
            // 模糊查询 类似于sql中的like
            Object conditionValue = searchDataInConditionDTO.getValue();
            if(conditionValue != null && StringUtil.isNotEmpty(conditionValue.toString())){
                String name = "data."+ attr;
                if (Objects.equals(ComboTypeEnum.CUSTOM.getType(), linkFieldAttr.getComboType())
                        && ExplainUtil.isCombo(linkFieldAttr.getFieldType())) {
                    List<ItemDataPoJo> list = baseFormDataService.getItemList(linkFieldAttr.getItems(), conditionValue);
                    list.forEach(item->{
                        item.setValue(item.getText());
                    });
                    searchDataInConditionVO.setItems(new ArrayList<>());
                    searchDataInConditionVO.setDepartmentList(new JSONArray());
                    searchDataInConditionVO.setItems(list);
                    return searchDataInConditionVO;
                }
                QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(name, conditionValue);
                boolQueryBuilder.filter(queryBuilder);
            }
            String  field = "data."+attr;
            if(FieldTypeEnum.TEXT.getEsalias().equals(attr.split(UNDERLINE)[0]) || FieldTypeEnum.SERIALNO.getAlias().equals(attr) ){
                field = field + ".keyword";
            }
            boolQueryBuilder.filter(existsQuery(field.replace(".keyword", "")));
            boolQueryBuilder.mustNot(termQuery(field, ""));
            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);


            NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
            FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(linkFieldAttr.getFieldType());
            TopHitsDTO topHitsDTO = new TopHitsDTO();
            topHitsDTO.setSearchQuery(searchQuery);
            topHitsDTO.setField("data."+relyPoJo.getLinkField());
            topHitsDTO.setFieldTypeEnum(fieldTypeEnum);
            topHitsDTO.setSaasMark(relyPoJo.getSourceSaasMark());
            topHitsDTO.setBusinessType(relyPoJo.getSourceBusinessType());

            List<PaasFormDataEntityExt> dataList = esHelper.topHits(topHitsDTO, indexTypeEnum);
            if (dataList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
            BeanUtil.copyProperties(searchDataInConditionDTO, userAndDepartmentGetDTO);
            userAndDepartmentGetDTO.setExplainList(explainList);
            // TODO getItemDataList新增了最后一个参数，目前传null，需要确认 by HU
            List<ItemDataPoJo> list = getItemDataList(userAndDepartmentGetDTO, dataList, linkFieldAttr,
                    relyPoJo.getSourceSaasMark(), relyPoJo.getSourceBusinessType(), relyPoJo.getSourceFormId(), null);
            searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("distinctData数据联动检索数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return searchDataInConditionVO;
    }

    @Override
    public SearchDataInConditionVO linkRelyList(SearchDataInConditionDTO searchDataInConditionDTO) throws XbbException{
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        try {
            String corpid = searchDataInConditionDTO.getCorpid();
            List<String> featureList = packageHelp.getFeatureList(corpid);
            if (!featureList.contains(FeaturesEnum.DATARELY.getAlias())) {
                // 该公司的套餐，没有这个功能
                searchDataInConditionVO.setItems(new ArrayList<>());
                searchDataInConditionVO.setDepartmentList(new JSONArray());
                return searchDataInConditionVO;
            }
            RelyPoJo relyPoJo = searchDataInConditionDTO.getRely();
            if (StockConstant.OLD_STOCK_TYPE_LIST.contains(relyPoJo.getSourceBusinessType())) {
                if (Objects.equals(relyPoJo.getSourceBusinessType(), XbbRefTypeEnum.INSTOCK.getCode())) {
                    relyPoJo.setSourceBusinessType(XbbRefTypeEnum.OTHER_INSTOCK.getCode());
                } else if (Objects.equals(relyPoJo.getSourceBusinessType(), XbbRefTypeEnum.OUTSTOCK.getCode())) {
                    relyPoJo.setSourceBusinessType(XbbRefTypeEnum.OTHER_OUTSTOCK.getCode());
                }
            }
//            Integer linkFieldType = relyPoJo.getLinkFieldType();
            if (Objects.equals(relyPoJo.getLinkFieldType(), FieldTypeEnum.SELECT_PRODUCT.getType())) {
                searchDataInConditionVO.setItems(new ArrayList<>());
                searchDataInConditionVO.setDepartmentList(new JSONArray());
                return searchDataInConditionVO;
            }
            // 获取联动表单的字段信息
            FieldAttrEntity linkFieldAttr = new FieldAttrEntity();

            FieldAttrEntity targetFieldEntity = new FieldAttrEntity();

            PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(corpid, relyPoJo.getSourceFormId(), relyPoJo.getSourceBusinessType());
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainAndDataIdMap(paasFormExplainEntity.getExplains(), null);
            List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            if (!explainMap.containsKey(relyPoJo.getLinkField())) {
                searchDataInConditionVO.setItems(new ArrayList<>());
                searchDataInConditionVO.setDepartmentList(new JSONArray());
                return searchDataInConditionVO;
            }
            Integer linkFieldType = explainMap.get(relyPoJo.getLinkField()).getFieldType();// 联动显示字段类型

            // 多条件改造
            Map<String, RelyConditionPoJo> conditionMap = new HashMap<>();
            boolean conditionFlag = Objects.nonNull(relyPoJo.getCondition()) && !relyPoJo.getCondition().isEmpty();
            if (conditionFlag) {
                List<RelyConditionPoJo> conditions = relyPoJo.getCondition();
                for (RelyConditionPoJo conditionPoJo : conditions) {
                    conditionMap.put(conditionPoJo.getDisplayField(), conditionPoJo);
                }
//                // 判断太麻烦，不如直接查吧
//                PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(corpid, relyPoJo.getSourceFormId(), relyPoJo.getSourceBusinessType());
//                explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
//                explainMap = ExplainUtil.getExplainMapByList(explainList, null);
            } else {
//                Integer targetFieldType = relyPoJo.getTargetFieldType();
                Integer targetFieldType = explainMap.get(relyPoJo.getTargetField()).getFieldType();
                Integer linkedFieldType = explainMap.get(relyPoJo.getLinkField()).getFieldType();
                boolean isDate = Objects.equals(FieldTypeEnum.DATETIME.getType(), linkFieldType) || Objects.equals(FieldTypeEnum.DATETIME.getType(), targetFieldType);
                boolean isLinkData = Objects.equals(FieldTypeEnum.LINK_DATA.getType(), linkFieldType) || Objects.equals(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType(), targetFieldType)
                        || Objects.equals(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType(), linkFieldType) || Objects.equals(FieldTypeEnum.LINK_DATA.getType(), targetFieldType)
                        || Objects.equals(FieldTypeEnum.LINK_DATA_MULTI.getType(), linkFieldType) || Objects.equals(FieldTypeEnum.LINK_DATA_MULTI.getType(), targetFieldType);
                if (Objects.isNull(linkFieldType) || ExplainUtil.isCombo(linkFieldType)
                        || Objects.isNull(targetFieldType) || ExplainUtil.isCombo(targetFieldType) || ExplainUtil.isSubForm(linkFieldType) || isDate || isLinkData) {
//                    // 当字段类型为空或者单选框，复选框，下拉框，下拉复选，子表单，日期，关联数据以及系统关联单选时，查下目标表单
//                    PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(corpid, relyPoJo.getSourceFormId(), relyPoJo.getSourceBusinessType());
//
//                    explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
//                    explainMap = ExplainUtil.getExplainMapByList(explainList, null);

                } else {
                    explainList.clear();
                    explainMap.clear();
                    linkFieldAttr.setAttr(relyPoJo.getLinkField());
//                    linkFieldAttr.setFieldType(relyPoJo.getLinkFieldType());
                    linkFieldAttr.setFieldType(linkedFieldType);
                    explainMap.put(relyPoJo.getLinkField(), linkFieldAttr);
                    targetFieldEntity.setAttr(relyPoJo.getTargetField());
//                    targetFieldEntity.setFieldType(relyPoJo.getTargetFieldType());
                    targetFieldEntity.setFieldType(targetFieldType);
                    explainMap.put(relyPoJo.getTargetField(), targetFieldEntity);
                    explainList.add(linkFieldAttr);
                    explainList.add(targetFieldEntity);
                }
            }

            // 增加一个id字段
            FieldAttrEntity dataIdFieldAttrEntity = new FieldAttrEntity();
            dataIdFieldAttrEntity.setAttr(FieldTypeEnum.DATAID.getAlias());
            dataIdFieldAttrEntity.setAttrName(FieldTypeEnum.DATAID.getAlias());
            dataIdFieldAttrEntity.setFieldType(FieldTypeEnum.DATAID.getType());
            explainMap.put(FieldTypeEnum.DATAID.getAlias(), dataIdFieldAttrEntity);
            linkFieldAttr = explainMap.get(relyPoJo.getLinkField());
            if(linkFieldAttr == null) {
                searchDataInConditionVO.setItems(new ArrayList<>());
                searchDataInConditionVO.setDepartmentList(new JSONArray());
                return searchDataInConditionVO;
            }
            if (Objects.equals(linkFieldAttr.getSaasAttr(), ProductEnum.UNIT.getSaasAttr()) && Objects.equals(relyPoJo.getSourceBusinessType(), XbbRefTypeEnum.PRODUCT.getCode())) {
                List<ItemPoJo> productItems = saasFormHelp.getProductItems(corpid);
                linkFieldAttr.setItems(productItems);
            }

            // 本表单
            Map<String, FieldAttrEntity> displayExplainListMap;
            if (CollectionsUtil.isEmpty(searchDataInConditionDTO.getPreviewFieldList())) {
                PaasFormExplainEntity displayFormExplain = proFormHelp.getExplainEntity(corpid, searchDataInConditionDTO.getFormId(), searchDataInConditionDTO.getBusinessType());
                displayExplainListMap = ExplainUtil.getExplainMap(displayFormExplain.getExplains(), null); // 当前表单字段解释
            } else {
                displayExplainListMap = ExplainUtil.getExplainMapByList(searchDataInConditionDTO.getPreviewFieldList(), null);
            }
            FieldAttrEntity thisFieldAttrEntity = displayExplainListMap.get(searchDataInConditionDTO.getAttr()); // 当前表单设置了数据联动的字段

            if(thisFieldAttrEntity == null) {
                searchDataInConditionVO.setItems(new ArrayList<>());
                searchDataInConditionVO.setDepartmentList(new JSONArray());
                return searchDataInConditionVO;
            }
            Boolean labelFlag = false;
            Integer fieldType = thisFieldAttrEntity.getFieldType();
            if (ExplainUtil.isSubForm(fieldType)) {
                List<? extends FieldAttrEntity> jsonArray = thisFieldAttrEntity.getSubForm().getItems();
                for (int i = 0; i < jsonArray.size(); i++) {
                    FieldAttrEntity subForm = jsonArray.get(i);
                    if (Objects.equals(subForm.getAttr(), searchDataInConditionDTO.getSubAttr())){
                        fieldType = subForm.getFieldType();
                        break;
                    }
                }
            } else if (Objects.equals(FieldTypeEnum.LABEL.getType(), fieldType)){
                labelFlag = true;
            }
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            // 获取下拉框的查询条件
            if (Objects.nonNull(searchDataInConditionDTO.getRelyBoolQueryBuilder())) {
                boolQueryBuilder = searchDataInConditionDTO.getRelyBoolQueryBuilder();
            }
            //解析查询条件
            boolQueryBuilder.filter(termQuery("corpid.keyword", searchDataInConditionDTO.getCorpid()));
            boolQueryBuilder.filter(termQuery("appId", relyPoJo.getSourceAppId()));
            boolQueryBuilder.filter(termQuery("formId", relyPoJo.getSourceFormId()));
            boolQueryBuilder.filter(termQuery("del", searchDataInConditionDTO.getDel()));

            // 获取权限内的数据
            searchDataInConditionDTO.setDefaultGroup(1);
            searchDataInConditionDTO.setListGroupId(ListGroupEnum.ALL.getCode().longValue());
            searchDataInConditionDTO.setSaasMark(relyPoJo.getSourceSaasMark());
            searchDataInConditionDTO.setBusinessType(relyPoJo.getSourceBusinessType());
            searchDataInConditionDTO.setSubBusinessType(relyPoJo.getSourceBusinessType());
            searchDataInConditionDTO.setFormId(relyPoJo.getSourceFormId());
            saasListHelp.packageSearchDataCondition(searchDataInConditionDTO);
            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(searchDataInConditionDTO.getCorpid(), relyPoJo.getSourceBusinessType(), relyPoJo.getSourceSaasMark());

            // 地址查询条件封装
            List<List<ConditionsEntityExt>> shouldConditions = new ArrayList<>();
            AddressUtil.addressSearchCondition(searchDataInConditionDTO.getConditionsList(), shouldConditions);
            searchDataInConditionDTO.getShouldConditionsList().addAll(shouldConditions);
            EsUtil.parseCondition(boolQueryBuilder,searchDataInConditionDTO.getConditionsList(),"",searchDataInConditionDTO.getCorpid(),relyPoJo.getSourceBusinessType());
            BoolQueryBuilder boolQuery = boolQuery();
            EsUtil.parseShouldCondition(boolQuery,searchDataInConditionDTO.getShouldConditionsList(),"",searchDataInConditionDTO.getCorpid(),relyPoJo.getSourceBusinessType());
            boolQueryBuilder.filter(boolQuery);
            // 共享权限
            EsUtil.parseSharePermissionCondition(boolQueryBuilder, searchDataInConditionDTO.getSharePermission(), searchDataInConditionDTO.getCorpid(), searchDataInConditionDTO.getBusinessType(), false);

            Object[] displayFieldValueList = searchDataInConditionDTO.getDisplayFieldValue();
            boolean searchParentProduct = true;
            if (Objects.nonNull(displayFieldValueList)) {
                for (Object value : searchDataInConditionDTO.getDisplayFieldValue()) {
                    // 判断是否是同一表单
                    FieldAttrEntity fieldAttrEntity;
                    if (conditionFlag) {
                        if (value instanceof Map) {
                            Map<String, Object> valueMap = (Map) value;
                            value = valueMap.get("value");
                            String attr = valueMap.get("displayField").toString();
                            RelyConditionPoJo relyConditionPoJo = conditionMap.get(attr);
                            relyPoJo.setDisplayField(relyConditionPoJo.getDisplayField());
                            relyPoJo.setTargetField(relyConditionPoJo.getTargetField());
                            relyPoJo.setTargetFieldType(relyConditionPoJo.getTargetFieldType());
                        }
                    }

                    targetFieldEntity = explainMap.get(relyPoJo.getTargetField());
                    if(targetFieldEntity == null) {
                        searchDataInConditionVO.setItems(new ArrayList<>());
                        searchDataInConditionVO.setDepartmentList(new JSONArray());
                        return searchDataInConditionVO;
                    }

                    if (relyPoJo.getDisplayField().contains(StringConstant.POINT)) {
                        String[] attrArray = relyPoJo.getDisplayField().split("\\.");
                        FieldAttrEntity subFormField = displayExplainListMap.get(attrArray[0]);
                        Map<String, FieldAttrEntity> subFormMap = ExplainUtil.getExplainMapByList(subFormField.getSubForm().getItems());
                        fieldAttrEntity = subFormMap.get(attrArray[1]);
                    } else {
                        fieldAttrEntity = displayExplainListMap.get(relyPoJo.getDisplayField());
                    }
                    if(fieldAttrEntity == null) {
                        searchDataInConditionVO.setItems(new ArrayList<>());
                        searchDataInConditionVO.setDepartmentList(new JSONArray());
                        return searchDataInConditionVO;
                    }
                    proConditionHelp.validateTheForm(fieldAttrEntity, targetFieldEntity, relyPoJo.getSourceBusinessType());
                    if (proConditionHelp.isEmpty(value, fieldAttrEntity.getFieldType())) {
                        EsUtil.isNull(targetFieldEntity.getFieldType(), boolQueryBuilder, relyPoJo.getTargetField());
                    } else {

                        if (ProConditionHelp.validateIsLinkData(fieldAttrEntity.getFieldType(), targetFieldEntity.getFieldType()) && value instanceof Map) {
                            Map<String, Object> map = (Map)((Map) value).get(StringConstant.JSON_DATA);
                            if (map == null) {
                                continue;
                            }
                            LinkInfoPojo linkInfoPojo = fieldAttrEntity.getLinkInfo();
                            if (Objects.isNull(linkInfoPojo)) {
                                searchDataInConditionVO.setItems(new ArrayList<>());
                                searchDataInConditionVO.setDepartmentList(new JSONArray());
                                return searchDataInConditionVO;
                            }
                            value = map.get(linkInfoPojo.getLinkKey());
                        }
                        if (proConditionHelp.isEmpty(value, fieldAttrEntity.getFieldType())) {
                            EsUtil.isNull(targetFieldEntity.getFieldType(), boolQueryBuilder, relyPoJo.getTargetField());
                        } else {
                            // 目标表单需要等于的值进行拼装es
                            proConditionHelp.needEqual(value, boolQueryBuilder, relyPoJo.getSourceFormId(), relyPoJo.getSourceSaasMark(),relyPoJo.getSourceBusinessType(), targetFieldEntity, fieldAttrEntity, corpid);
                        }
                    }
                }
            }
            if (conditionFlag) {
                // 数据联动多条件，需要判断是否
                for(RelyConditionPoJo relyConditionPoJo: relyPoJo.getCondition()) {
                    String targetField = relyConditionPoJo.getTargetField();
                    FieldAttrEntity subField = null;
                    if (targetField.contains(".")) {
                        List<String> targetFieldList = ExplainUtil.getAttrByPoint(targetField);
                        List<? extends FieldAttrEntity> subFieldList = explainMap.get(targetFieldList.get(0)).getSubForm().getItems();
                        for (FieldAttrEntity item : subFieldList) {
                            if (Objects.equals(item.getAttr(), targetFieldList.get(1))) {
                                subField = item;
                                break;
                            }
                        }
                    } else {
                        subField = explainMap.get(targetField);
                    }
                    if (proConditionHelp.validateLinkData(subField.getFieldType())) {
                        searchParentProduct = false;
                        break;
                    }
                }
            } else {
                if (Objects.nonNull(targetFieldEntity) && Objects.nonNull(targetFieldEntity.getFieldType()) && proConditionHelp.validateLinkData(targetFieldEntity.getFieldType())) {
                    searchParentProduct = false;
                }
            }
            if (searchParentProduct) {
                // 当传过来的数据不是id时，产品搜父产品的就可以
                productCondition(boolQueryBuilder,relyPoJo.getSourceBusinessType(), relyPoJo.getSourceBusinessType(), "");
            }
            // 模糊查询 类似于sql中的like
            likeBoolQuery(searchDataInConditionDTO.getValue(), explainMap.get(relyPoJo.getLinkField()), corpid,
                    relyPoJo.getSourceFormId(), relyPoJo.getSourceBusinessType(), relyPoJo.getSourceSaasMark(), boolQueryBuilder);

            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, indexTypeEnum.getType()));
            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
            NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
            // 根据需要显示的字段去获取es前缀
            FieldTypeEnum sourceFieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(linkFieldAttr.getFieldType());

            // 联动显示的值
            List<String> source = new ArrayList<>();
            List<SubRelyFieldPojo> subRelyFieldList = relyPoJo.getSubRelyFieldList();
            List<PaasFormDataEntityExt> dataList;
            if (Objects.isNull(subRelyFieldList) || subRelyFieldList.isEmpty()) {
                // 子表单外数据联动
                if (ExplainUtil.isCombo(fieldType)) {
                    // 下拉框、单选按钮、复选框、下拉复选
                    TopHitsDTO topHitsDTO = new TopHitsDTO();
                    BeanUtil.copyProperties(searchDataInConditionDTO, topHitsDTO);
                    topHitsDTO.setFieldTypeEnum(sourceFieldTypeEnum);
                    topHitsDTO.setSearchQuery(searchQuery);
                    topHitsDTO.setSaasMark(relyPoJo.getSourceSaasMark());
                    topHitsDTO.setBusinessType(relyPoJo.getSourceBusinessType());
                    topHitsDTO.setField("data."+relyPoJo.getLinkField());
                    //阶段推进器需要阶段流程id定位数据版本
                    if (Objects.equals(FieldTypeEnum.STAGE_THRUSTER.getType(), linkFieldType)) {
                        List<String> fieldList = new ArrayList<>();
                        fieldList.add("data." + relyPoJo.getLinkField());
                        fieldList.add("data." + PaasStageEnum.STAGE_PROCESS_ID.getAttr());
                        topHitsDTO.setSource(fieldList);
                    }
                    dataList = esHelper.topHits(topHitsDTO, indexTypeEnum);
                    if (dataList == null) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                    }
                } else {
                    // 其他字段
                    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
                    //设置查询条件
                    sourceBuilder.query(searchQuery.getQuery());
                    List<String> fieldList = new ArrayList<>();
                    fieldList.add(relyPoJo.getLinkField());
                    if (Objects.equals(FieldTypeEnum.STAGE_THRUSTER.getType(), linkFieldAttr.getFieldType())) {
                        fieldList.add(PaasStageEnum.STAGE_PROCESS_ID.getAttr());
                    }
                    sourceBuilder.sort(new FieldSortBuilder(FieldTypeEnum.UPDATETIME.getAlias()).order(SortOrder.DESC));
                    dataList = paasEsModel.list(sourceBuilder, indexTypeEnum, fieldList, 1, 1);
                }
            } else {
                // 子表单数据联动
                source.add(BasicConstant.DATA);
                subRelyFieldList.forEach(item->{
                    source.add(relyPoJo.getLinkField() + StringConstant.POINT + item.getTargetField());
                });
                //解析查询条件
                boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
                boolQueryBuilder.filter(termQuery("formId", relyPoJo.getSourceFormId()));
                boolQueryBuilder.filter(termQuery("del", 0));
                SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
                // 排序
                sourceBuilder.sort(new FieldSortBuilder(FieldTypeEnum.UPDATETIME.getAlias()).order(SortOrder.DESC));
                sourceBuilder.query(boolQueryBuilder);
                PaasFormDataEsListVO paasFormDataEsListVO = paasEsModel.list(indexTypeEnum, relyPoJo.getSourceBusinessType(), sourceBuilder,source, 1, 1);
                if (Objects.isNull(paasFormDataEsListVO)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                dataList = paasFormDataEsListVO.getPaasFormDataESList();
            }
            UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
            BeanUtil.copyProperties(searchDataInConditionDTO, userAndDepartmentGetDTO);
            userAndDepartmentGetDTO.setExplainList(explainList);
            Integer saasMark = relyPoJo.getSourceSaasMark();
            Integer businessType = relyPoJo.getSourceBusinessType();
            Long formId = relyPoJo.getSourceFormId();
            if(labelFlag){
                if (Objects.equals(thisFieldAttrEntity.getFieldType(), FieldTypeEnum.LABEL.getType())) {
                    List<ItemDataPoJo> list = getLabelDataList(searchDataInConditionDTO.getCorpid(), searchDataInConditionDTO.getFormId(), dataList, linkFieldAttr.getAttr());
                    searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
                }
            }else if (Objects.isNull(subRelyFieldList) || subRelyFieldList.isEmpty()) {
                if (ExplainUtil.isSubForm(thisFieldAttrEntity.getFieldType())) {
                    List<? extends FieldAttrEntity> jsonArray = thisFieldAttrEntity.getSubForm().getItems();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        FieldAttrEntity subForm = jsonArray.get(i);
                        if (Objects.equals(subForm.getAttr(), searchDataInConditionDTO.getSubAttr())){
                            thisFieldAttrEntity = subForm; // 如果thisFieldAttrEntity是子表单的话，SubAttr才是子表单内设置了数据联动的子字段
                            break;
                        }
                    }
                }
                List<ItemDataPoJo> list = getItemDataList(userAndDepartmentGetDTO, dataList, linkFieldAttr, saasMark, businessType, formId, thisFieldAttrEntity);
                searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
            } else {
                // 获取子表单字段
                List<FieldAttrEntity> subLinkExplainList = (List<FieldAttrEntity>) linkFieldAttr.getSubForm().getItems();
                Iterator<FieldAttrEntity> iterator = subLinkExplainList.iterator();
                Map<String, FieldAttrEntity> subLinkExplainMap = new HashMap<>(subLinkExplainList.size());
                while (iterator.hasNext()) {
                    FieldAttrEntity fieldAttrEntity = iterator.next();
                    String parent = fieldAttrEntity.getParentAttr();
                    if (StringUtil.isNotEmpty(parent)) {
                        parent = parent + StringConstant.POINT;
                    }
                    if (!source.contains(parent + fieldAttrEntity.getAttr())) {
                        iterator.remove();
                        continue;
                    }
                    subLinkExplainMap.put(fieldAttrEntity.getAttr(), fieldAttrEntity);
                }
                // 查询子表单数据

                List<String> subFieldList = new ArrayList<>();
                subRelyFieldList.forEach(item->{
                    subFieldList.add(item.getTargetField());
                });
                subFieldList.add("attr");
                List<Long> ids = new ArrayList<>();
                dataList.forEach(item -> ids.add(item.getId()));
                BoolQueryBuilder subBoolQueryBuilder = boolQuery();
                subBoolQueryBuilder.filter(termQuery("corpid.keyword", searchDataInConditionDTO.getCorpid()))
                        .filter(termQuery("formId", relyPoJo.getSourceFormId()))
                        .filter(termQuery("del", searchDataInConditionDTO.getDel()))
                        .filter(termsQuery(BasicConstant.DATAID, ids))
                        .filter(termQuery(StringConstant.ATTR + StringConstant.POINT + StringConstant.KEY_WORD, linkFieldAttr.getAttr()));
                IndexTypeEnum subIndexTypeEnum = IndexTypeEnum.getSubEnum(indexTypeEnum);
                List<PaasFormSubDataEntity> subDataEntities = paasFormSubDataEsModel.getSubDataList(subBoolQueryBuilder, subIndexTypeEnum, subFieldList, 1, 200, PaasFormSubDataEntity.class);
                Map<Long, Map<String, JSONArray>> subMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (PaasFormSubDataEntity subDataEntity : subDataEntities) {
                    JSONObject data = subDataEntity.getData() == null ? new JSONObject(): subDataEntity.getData();
                    data.put(BusinessConstant.SUB_DATA_ID, subDataEntity.getId());
                    subDataEntity.setData(data);
                    subMap.computeIfAbsent(subDataEntity.getDataId(), v -> new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY)).computeIfAbsent(subDataEntity.getAttr(), v -> new JSONArray()).add(data);
                }
                dataList.forEach(item -> {
                    Map<String, JSONArray> subData = subMap.get(item.getId());
                    if (Objects.nonNull(subData)) {
                        subData.forEach((k, v) -> item.getData().put(k, v));
                    }
                });

                // 获取本表单字段的子表单字段
                List<? extends FieldAttrEntity> subDisplayExplainList = displayExplainListMap.get(searchDataInConditionDTO.getAttr()).getSubForm().getItems();
                Map<String, FieldAttrEntity> subDisplayExplainMap = ExplainUtil.getExplainMapByList(subDisplayExplainList);
                List<SubRelyFieldPojo> list = relyPoJo.getSubRelyFieldList();
                Map<String, String> thisToTarget = new HashMap<>(list.size());
                list.forEach(item->{
                    thisToTarget.put(item.getThisField(), item.getTargetField());
                });
                List<JSONObject> subDataList = new ArrayList<>();
                UserAndDepartmentGetVO userAndDepartmentGetVO = userHelp.getUserDepartmentMap(userAndDepartmentGetDTO);
                Map<String, UserEntity> userMap = userAndDepartmentGetVO.getUserMap();
                Map<String, DepartmentEntity> departmentMap = userAndDepartmentGetVO.getDepartmentMap();

                for (PaasFormDataEntityExt item : dataList) {
                    if (ExplainUtil.isSubForm(linkFieldAttr.getFieldType())) {
                        if (item.getData() == null) {
                            continue;
                        }
                        Object subFormObject = item.getData().get(linkFieldAttr.getAttr());
                        subDataList = JSON.parseArray(JSON.toJSONString(subFormObject), JSONObject.class);
                        if (Objects.isNull(subDataList)) {
                            continue;
                        }
                        for (int i = 0; i < subDataList.size(); i++) {
                            JSONObject data = subDataList.get(i);
                            ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
                            parseSingleRowDataDTO.setUserMap(userMap);
                            parseSingleRowDataDTO.setDepartmentMap(departmentMap);
                            parseSingleRowDataDTO.setDataJsonObject(data);
                            parseSingleRowDataDTO.setExplainMap(subLinkExplainMap);
                            parseSingleRowDataDTO.setLoginUser(searchDataInConditionDTO.getLoginUser());
                            ParseSingleRowDataVO parseSingleRowDataVO = formDataUpdateGetAnalysisDataHelp.parseSingleRowData(parseSingleRowDataDTO);
                            // 获取关联数据的信息
                            JSONObject result = parseSingleRowDataVO.getResult();
                            LinkResultDataVO linkResultDataVO = parseSingleRowDataVO.getLinkResultDataVO();
                            if ( linkResultDataVO != null && !linkResultDataVO.getLinkData().isEmpty() && !linkResultDataVO.getLinkDataSet().isEmpty() ) {
                                FormDataUpdateGetDTO formDataGetDTO = new FormDataUpdateGetDTO();
                                formDataGetDTO.setCorpid(corpid);
                                formDataGetDTO.setLoginUser(searchDataInConditionDTO.getLoginUser());
                                linkResultDataVO.setData(result);
                                linkResultDataVO.setExplainMap(subLinkExplainMap);
                                linkResultDataVO.setUserMap(userMap);
                                linkResultDataVO.setDepartmentMap(departmentMap);
                                linkResultDataVO.setExplainList(subLinkExplainList);
                                result = formDataLinkDataUpdateGetService.formDataLinkDataGet(formDataGetDTO, linkResultDataVO);
                            }

                            JSONObject thisData = new JSONObject();
                            // 遍历当前表单对应目标表单的字段，通过对应关系拿到数据
                            Iterator<String> stringIterator = thisToTarget.keySet().iterator();
                            while (stringIterator.hasNext()) {
                                String thisKey = stringIterator.next();
                                // 获取对应的字段
                                String key = thisToTarget.get(thisKey);
                                if (Objects.isNull(result.get(key))) {
                                    continue;
                                }
                                FieldAttrEntity displayField = subDisplayExplainMap.get(thisKey);
                                if(displayField == null) {
                                    searchDataInConditionVO.setItems(new ArrayList<>());
                                    searchDataInConditionVO.setDepartmentList(new JSONArray());
                                    return searchDataInConditionVO;
                                }
                                Integer thisKeyFieldType = displayField.getFieldType();
                                FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(thisKeyFieldType);
                                switch (fieldTypeEnum) {
                                    case TEXT:
                                    case TEXTAREA:
                                        if (result.get(key) instanceof Map || result.get(key) instanceof ItemPoJo) {
                                            thisData.put(thisKey, result.getJSONObject(key).get("text"));
                                        }else {
                                            thisData.put(thisKey, result.get(key));
                                        }
                                        break;
                                    case COMBO:
                                    case RADIO_GROUP:
                                        if (!(result.get(key) instanceof Map) && !(result.get(key) instanceof ItemPoJo)) {
                                            // 单行文本一类的数据
                                            JSONObject itemJSON = new JSONObject();
                                            itemJSON.put("value", result.get(key));
                                            itemJSON.put("text", result.get(key));
                                            thisData.put(thisKey, itemJSON);
                                        } else {
                                            // 下拉框、单选按钮一类的数据
                                            JSONObject itemJSON = new JSONObject();
                                            Object value = result.getJSONObject(key).get("text");
                                            itemJSON.put("value", value);
                                            itemJSON.put("text", value);
                                            thisData.put(thisKey, itemJSON);
                                        }
                                        break;
                                    case COMBO_CHECK:
                                    case CHECKBOX_GROUP:
                                        if (result.get(key) instanceof List) {
                                            // 下拉多选和复选一类数据
                                            JSONArray jsonArray = result.getJSONArray(key);
                                            for (int j = 0; j < jsonArray.size(); j++) {
                                                JSONObject jsonObject = jsonArray.getJSONObject(j);
                                                jsonObject.put("value", jsonObject.get("text"));
                                                jsonArray.set(j, jsonObject);
                                            }
                                            thisData.put(thisKey, jsonArray);
                                        } else if (result.get(key) instanceof Map || result.get(key) instanceof ItemPoJo) {
                                            // 下拉框、单选按钮一类的数据
                                            JSONObject itemJSON = new JSONObject();
                                            Object value = result.getJSONObject(key).get("text");
                                            itemJSON.put("value", value);
                                            itemJSON.put("text", value);
                                            JSONArray jsonArray = new JSONArray();
                                            jsonArray.add(itemJSON);
                                            thisData.put(thisKey, jsonArray);
                                        } else {
                                            // 单行文本一类的数据
                                            JSONObject itemJSON = new JSONObject();
                                            Object value = result.get(key);
                                            itemJSON.put("value", value);
                                            itemJSON.put("text", value);
                                            JSONArray jsonArray = new JSONArray();
                                            jsonArray.add(itemJSON);
                                            thisData.put(thisKey, jsonArray);
                                        }
                                        break;
                                    case LINK_DATA:
                                        thisData.put(thisKey, result.get(key));
                                        break;
                                    case LINK_DATA_MULTI:
                                        if (result.get(key) instanceof Map) {
                                            // 关联多选联动显示关联单选
                                            JSONArray resultArray = new JSONArray();
                                            resultArray.add(result.get(key));
                                            thisData.put(thisKey, resultArray);
                                        } else if (result.get(key) instanceof List) {
                                            // 关联多选联动显示关联多选
                                            thisData.put(thisKey, result.get(key));
                                        }
                                        break;
                                    default:
                                        thisData.put(thisKey, result.get(key));
                                        break;
                                }
                            }
                            subDataList.set(i, thisData);
                        }
                    }
                }

                searchDataInConditionVO.setDataList(subDataList);
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("联动数据获取数据失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return searchDataInConditionVO;
    }

    @Override
    public List<ItemDataPoJo> getLabelDataList(String corpid, Long formId, List<PaasFormDataEntityExt> dataList, String linkFieldAttr) throws XbbException {
        List<ItemDataPoJo> list = new ArrayList<>();

        List<Long> labelIds = new ArrayList<>();
        for ( PaasFormDataEntityExt paasFormDataEntityExt : dataList ) {
            JSONObject jsonData = paasFormDataEntityExt.getData();
            if (Objects.isNull(jsonData)) {
                LOG.warn("DistinctDataServiceImpl.getLabelDataList data is null，id：" + paasFormDataEntityExt.getDataId());
                continue;
            }
            JSONArray jsonArray = jsonData.getJSONArray(linkFieldAttr);
            if (CollectionsUtil.isNotEmpty(jsonArray)) {
                labelIds.addAll(jsonArray.toJavaList(Long.class));
            }
        }
        List<LabelEntity> byLabelIds = null;
        if (CollectionsUtil.isNotEmpty(labelIds)) {
            byLabelIds = labelModel.getByLabelIds(labelIds, corpid);
        }
        if (CollectionsUtil.isNotEmpty(byLabelIds)) {
            List<String> names = new ArrayList<>();
            byLabelIds.forEach(item -> names.add(item.getName()));
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("formId", formId);
            param.put("nameIn", names);
            param.put("enable", BasicConstant.ZERO);
            param.put("del", DelEnum.NORMAL.getDel());
            List<LabelEntity> entitys = labelModel.findEntitys(param);
            List<LabelPojo> labelPojos = new ArrayList<>();
            for (LabelEntity entity : entitys) {
                LabelPojo labelPojo = new LabelPojo();
                labelPojo.setId(entity.getId());
                labelPojo.setName(entity.getName());
                labelPojo.setColor(entity.getColor());
                labelPojos.add(labelPojo);
            }
            ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
            itemDataPoJo.setText(labelPojos);
            itemDataPoJo.setValue(labelPojos);
            list.add(itemDataPoJo);
        }
        return list;
    }

    @Override
    public SearchDataInConditionVO listOfPublicGroup(FieldAttrEntity fieldAttrEntity, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) throws XbbException{
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        String corpid = searchDataInConditionDTO.getCorpid();
        Integer businessType = searchDataInConditionDTO.getBusinessType();
        Long formId = searchDataInConditionDTO.getFormId();
        try {
            if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {

                List<PublicGroupSeniorEntity> publicGroupSeniorEntityList = publicGroupSeniorModel.findEntityByStatus(corpid, formId, BasicConstant.ONE);
                List<ItemDataPoJo> items = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(publicGroupSeniorEntityList)) {
                    publicGroupSeniorEntityList.removeIf(item ->Objects.equals(item.getGroupType(),BasicConstant.TWO));
                    ItemDataPoJo itemDataPoJo;
                    for (PublicGroupSeniorEntity publicGroupSeniorEntity : publicGroupSeniorEntityList) {
                        itemDataPoJo = new ItemDataPoJo();
                        itemDataPoJo.setText(publicGroupSeniorEntity.getName());
                        itemDataPoJo.setValue(publicGroupSeniorEntity.getId());
                        items.add(itemDataPoJo);
                    }
                }
                searchDataInConditionVO.setItems(items);
            }
        } catch (Exception e) {
            LOG.error("获取分组失败",e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return searchDataInConditionVO;
    }

    @Override
    public SearchDataInConditionVO listOfText(ConditionExplainPojo conditionExplainPojo, FieldAttrEntity fieldAttrEntity, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) throws XbbException {
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        try {
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            //解析查询条件
            boolQueryBuilder.filter(termQuery("corpid.keyword", searchDataInConditionDTO.getCorpid()));
            if (searchDataInConditionDTO.getLimitForms()){
                boolQueryBuilder.filter(termsQuery("formId", searchDataInConditionDTO.getFormIdList()));
            }else {
                boolQueryBuilder.filter(termQuery("formId", searchDataInConditionDTO.getFormId()));
            }
            boolQueryBuilder.filter(termQuery("del", searchDataInConditionDTO.getDel()));
            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(searchDataInConditionDTO.getCorpid(), searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getSaasMark());
            EsUtil.parseCondition(boolQueryBuilder,searchDataInConditionDTO.getConditionsList(),"",searchDataInConditionDTO.getCorpid(),searchDataInConditionDTO.getBusinessType());
            EsUtil.parseShouldCondition(boolQueryBuilder,searchDataInConditionDTO.getShouldConditionsList(),"",searchDataInConditionDTO.getCorpid(),searchDataInConditionDTO.getBusinessType());
            // 共享权限
            EsUtil.parseSharePermissionCondition(boolQueryBuilder, searchDataInConditionDTO.getSharePermission(), searchDataInConditionDTO.getCorpid(), searchDataInConditionDTO.getBusinessType(), false);
            productCondition(boolQueryBuilder,searchDataInConditionDTO.getBusinessType(),searchDataInConditionDTO.getSubBusinessType(),fieldAttrEntity.getAttr());
            String subAttr = searchDataInConditionDTO.getSubAttr();
            String attr = searchDataInConditionDTO.getAttr();
            String originalAttr = searchDataInConditionDTO.getOriginalAttr();
            if (StringUtil.isNotEmpty(originalAttr)) {
                attr = originalAttr;
            }
            // 模糊查询 类似于sql中的like
            Object conditionValue = searchDataInConditionDTO.getValue();
            if(conditionValue != null && StringUtil.isNotEmpty(conditionValue.toString())){
                String name;
                if(StringUtil.isNotEmpty(subAttr)){
                    name = "data."+ attr + "." + subAttr;
                }else {
                    name = "data."+ attr;
                }
                QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(name, searchDataInConditionDTO.getValue());
                boolQueryBuilder.filter(queryBuilder);
            }
            String field;
            String name = "";
            if(StringUtil.isNotEmpty(subAttr)){
                field = "data."+attr+ "." +subAttr;
            }else{
                field = "data."+attr;
            }
            if(FieldTypeEnum.TEXT.getEsalias().equals(attr.split(UNDERLINE)[0]) || FieldTypeEnum.TEXT.getEsalias().equals(subAttr.split(UNDERLINE)[0])
                || FieldTypeEnum.SERIALNO.getAlias().equals(attr) || FieldTypeEnum.TEXT.getAlias().equals(subAttr)){
                name = field + ".keyword";
            }
            boolQueryBuilder.filter(existsQuery(name.replace(".keyword", "")));
            boolQueryBuilder.mustNot(termQuery(name, ""));
            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
            NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
            TopHitsDTO topHitsDTO = new TopHitsDTO();
            BeanUtil.copyProperties(searchDataInConditionDTO, topHitsDTO);
            topHitsDTO.setSearchQuery(searchQuery);
            topHitsDTO.setField(field) ;
            topHitsDTO.setFieldTypeEnum(fieldTypeEnum);
            topHitsDTO.setSaasMark(searchDataInConditionDTO.getSaasMark());
            topHitsDTO.setBusinessType(searchDataInConditionDTO.getBusinessType());
            List<PaasFormDataEntityExt> dataList = esHelper.topHits(topHitsDTO, indexTypeEnum);
            if (dataList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            List<ItemDataPoJo> list = new ArrayList<>();
            for (PaasFormDataEntityExt paasFormDataEsEntity: dataList) {
                JSONObject data = paasFormDataEsEntity.getData();
                Iterator iterator = data.keySet().iterator();
                while (iterator.hasNext()){
                    ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                    String key = iterator.next().toString();
                    if (key.equals(attr)) {
                        if(StringUtil.isNotEmpty(searchDataInConditionDTO.getSubAttr())){
                            // 子表单逻辑
                            JSONArray subDataArray = data.getJSONArray(key);
                            for(int i=0; i<subDataArray.size(); i++) {
                                JSONObject subDataObject = subDataArray.getJSONObject(i);
                                Iterator subIterator = subDataObject.keySet().iterator();
                                while (subIterator.hasNext()){
                                    ItemDataPoJo subItemDataPoJo = new ItemDataPoJo();
                                    String  subKey = subIterator.next().toString();
                                    if(subKey.equals(searchDataInConditionDTO.getSubAttr())){
                                        Object value = subDataObject.get(subKey);
                                        Object text = ItemUtil.getText(value, fieldAttrEntity);
                                        if (Objects.isNull(text)) {
                                            continue;
                                        }
                                        subItemDataPoJo.setText(text);
                                        subItemDataPoJo.setValue(value);
                                        list.add(subItemDataPoJo);
                                    }
                                }
                            }
                        }else {
                            Object value = data.get(key);
                            Object text = ItemUtil.getText(value, fieldAttrEntity);
                            if (Objects.isNull(text)) {
                                continue;
                            }
                            itemDataPoJo.setText(text);
                            itemDataPoJo.setValue(value);
                            list.add(itemDataPoJo);
                        }
                    }
                }
            }
            Boolean isCombo = Objects.equals(FieldTypeEnum.COMBO.getType(), fieldAttrEntity.getFieldType())
                    || Objects.equals(FieldTypeEnum.COMBO_CHECK.getType(), fieldAttrEntity.getFieldType());
            if (isCombo) {
                conditionExplainPojo =baseFormDataService.getFieldAttr(searchDataInConditionDTO);
                Boolean subAttrFlag = false;
                fieldAttrEntity = conditionExplainPojo.getParentFieldAttr();
                if (StringUtil.isNotEmpty(searchDataInConditionDTO.getSubAttr())) {
                    subAttrFlag = true;
                    fieldAttrEntity = conditionExplainPojo.getSubFieldAttr();
                }
                List<ItemDataPoJo> itemDataList = baseFormDataService.getCustomList(searchDataInConditionDTO, fieldAttrEntity, subAttrFlag, conditionExplainPojo);
                itemDataList.forEach(item->{
                    item.setText(item.getText()+I18nMessageUtil.getMessage(I18nStringConstant.CUSTOMIZE));
                });
                list.addAll(itemDataList);
            }
            searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        } catch (Exception e) {
            LOG.error("distinctData检索文本字段出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return searchDataInConditionVO;
    }


    @Override
    public SearchDataInConditionVO listOfArray(FieldAttrEntity fieldAttrEntity, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) throws XbbException {
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        try {
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            //解析查询条件
            boolQueryBuilder.filter(termQuery("corpid.keyword", searchDataInConditionDTO.getCorpid()));
            if (searchDataInConditionDTO.getLimitForms()){
                boolQueryBuilder.filter(termsQuery("formId", searchDataInConditionDTO.getFormIdList()));
            }else {
                boolQueryBuilder.filter(termQuery("formId", searchDataInConditionDTO.getFormId()));
            }

            boolQueryBuilder.filter(termQuery("del", searchDataInConditionDTO.getDel()));
            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(searchDataInConditionDTO.getCorpid(), searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getSaasMark());
            EsUtil.parseCondition(boolQueryBuilder,searchDataInConditionDTO.getConditionsList(),"",searchDataInConditionDTO.getCorpid(),searchDataInConditionDTO.getBusinessType());
            EsUtil.parseShouldCondition(boolQueryBuilder,searchDataInConditionDTO.getShouldConditionsList(),"",searchDataInConditionDTO.getCorpid(),searchDataInConditionDTO.getBusinessType());
            // 共享权限
            EsUtil.parseSharePermissionCondition(boolQueryBuilder, searchDataInConditionDTO.getSharePermission(), searchDataInConditionDTO.getCorpid(), searchDataInConditionDTO.getBusinessType(), false);
            productCondition(boolQueryBuilder,searchDataInConditionDTO.getBusinessType(),searchDataInConditionDTO.getSubBusinessType(),fieldAttrEntity.getAttr());
            String subAttr = searchDataInConditionDTO.getSubAttr();
            String attr = searchDataInConditionDTO.getAttr();
            // 模糊查询 类似于sql中的like
            Object conditionValue = searchDataInConditionDTO.getValue();
            if(conditionValue != null && StringUtil.isNotEmpty(conditionValue.toString())){
                String name;
                if(StringUtil.isNotEmpty(subAttr)){
                    name = "data."+ attr + "." + subAttr;
                }else {
                    name = "data."+ attr;
                }
                QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(name, searchDataInConditionDTO.getValue());
                boolQueryBuilder.filter(queryBuilder);
            }
            String field;
            if(StringUtil.isNotEmpty(subAttr)){
                field = "data."+attr+ "." +subAttr;
            }else{
                field = "data."+attr;
            }

            boolQueryBuilder.mustNot(termQuery(field, ""));
            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
            NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
            TopHitsDTO topHitsDTO = new TopHitsDTO();
            BeanUtil.copyProperties(searchDataInConditionDTO, topHitsDTO);
            topHitsDTO.setSearchQuery(searchQuery);
            topHitsDTO.setField(field) ;
            topHitsDTO.setFieldTypeEnum(fieldTypeEnum);
            topHitsDTO.setSaasMark(searchDataInConditionDTO.getSaasMark());
            topHitsDTO.setBusinessType(searchDataInConditionDTO.getBusinessType());
            List<PaasFormDataEntityExt> dataList = esHelper.topHits(topHitsDTO, indexTypeEnum);
            if (dataList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            List<ItemDataPoJo> list = new ArrayList<>();
            for (PaasFormDataEntityExt paasFormDataEsEntity: dataList) {
                JSONObject data = paasFormDataEsEntity.getData();
                Iterator iterator = data.keySet().iterator();
                while (iterator.hasNext()){

                    String key = iterator.next().toString();
                    if (key.equals(searchDataInConditionDTO.getAttr())) {
                        if(StringUtil.isNotEmpty(searchDataInConditionDTO.getSubAttr())){
                            // 子表单逻辑
                            JSONArray subDataArray = data.getJSONArray(key);
                            for(int i=0; i<subDataArray.size(); i++) {
                                JSONObject subDataObject = subDataArray.getJSONObject(i);
                                Iterator subIterator = subDataObject.keySet().iterator();
                                while (subIterator.hasNext()){
                                    String  subKey = subIterator.next().toString();
                                    if(subKey.equals(searchDataInConditionDTO.getSubAttr())){
                                        JSONArray itemList = subDataObject.getJSONArray(subKey);
                                        if (Objects.nonNull(itemList)) {
                                            HashSet hashSet = new HashSet(itemList);
                                            Iterator<Object> iterator1 = hashSet.iterator();
                                            while (iterator1.hasNext()) {
                                                ItemDataPoJo subItemDataPoJo = new ItemDataPoJo();
                                                Object value = iterator1.next();
                                                Object text = ItemUtil.getText(value, fieldAttrEntity);
                                                if (Objects.isNull(text)) {
                                                    continue;
                                                }
                                                subItemDataPoJo.setText(text);
                                                subItemDataPoJo.setValue(value);
                                                list.add(subItemDataPoJo);
                                            }
                                        }
                                    }
                                }
                            }
                        }else {
                            JSONArray valueList = data.getJSONArray(key);
                            if (Objects.nonNull(valueList)) {
                                Iterator<Object> iterator1 = valueList.iterator();
                                while (iterator1.hasNext()) {
                                    Object value = iterator1.next();
                                    Object text = ItemUtil.getText(value, fieldAttrEntity);
                                    if (Objects.isNull(text)) {
                                        continue;
                                    }
                                    ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                                    itemDataPoJo.setText(text);
                                    itemDataPoJo.setValue(value);
                                    list.add(itemDataPoJo);
                                }
                            }
                        }
                    }
                }
            }
            searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        } catch (Exception e) {
            LOG.error("distinctData.listOfArray 检索文本字段出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return searchDataInConditionVO;
    }

    @Override
    public SearchDataInConditionVO listOfLinkBusiness(FieldAttrEntity fieldAttrEntity, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) throws XbbException {
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        try {
            if ((Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.PRODUCT.getCode()) && Objects.equals(searchDataInConditionDTO.getAttr(), ProductEnum.WAREHOUSE.getAttr()))
                || (Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.STOCK_FLOW_BILL.getCode()) && Objects.equals(searchDataInConditionDTO.getAttr(), StockFlowBillEnum.WAREHOUSE_ID.getAttr()))
                || (Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.BATCH_FLOW_BILL.getCode()) && Objects.equals(searchDataInConditionDTO.getAttr(), BatchFlowBillEnum.WAREHOUSE_ID.getAttr()))
                || (Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.SEQ_SEARCH.getCode()) && Objects.equals(searchDataInConditionDTO.getAttr(), ProductSerialBalanceEnum.WAREHOUSE_ID.getAttr()))
                || (Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.STOCK_STANDING_BOOK.getCode()) && Objects.equals(searchDataInConditionDTO.getAttr(), StockStandingBookEnum.WAREHOUSE_ID.getAttr()))) {
                searchDataInConditionDTO.setConditionsList(Collections.singletonList(new ConditionsEntityExt(FieldTypeEnum.FLOW_STATUS.getAlias(),"",FieldTypeEnum.FLOW_STATUS.getType(),ConditionEnum.IN.getSymbol(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType()))));
                listOfLinkWarehouse(searchDataInConditionVO, searchDataInConditionDTO, fieldTypeEnum);
                return searchDataInConditionVO;
            } else if (Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.PRODUCT.getCode()) && Objects.equals(searchDataInConditionDTO.getAttr(), ProductEnum.SUPPLIER.getAttr())) {
//                searchDataInConditionDTO.setConditionsList(Collections.singletonList(new ConditionsEntityExt(FieldTypeEnum.FLOW_STATUS.getAlias(),"",FieldTypeEnum.FLOW_STATUS.getType(),ConditionEnum.IN.getSymbol(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType()))));
                searchDataInConditionDTO.setShouldConditionsList(new ArrayList<>());
                listOfLinkSupplier(searchDataInConditionVO, searchDataInConditionDTO, fieldTypeEnum);
                return searchDataInConditionVO;
            }else if ((Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode())
                    && Objects.equals(searchDataInConditionDTO.getAttr(), CustomerCommunicateEnum.CUSTOMER_NAME.getAttr()))
                    || (Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.DISTRIBUTOR_ACCOUNT.getCode())
                    && Objects.equals(searchDataInConditionDTO.getAttr(), DistributorAccountEnum.DISTRIBUTOR_NAME.getAttr()))) {
                // 跟进记录搜索客户
                searchDataInConditionDTO.setShouldConditionsList(new ArrayList<>());
                listOfLinkCustomer(fieldAttrEntity,searchDataInConditionVO, searchDataInConditionDTO);
                return searchDataInConditionVO;
            }
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            //解析查询条件
            boolQueryBuilder.filter(termQuery("corpid.keyword", searchDataInConditionDTO.getCorpid()));
            if(Objects.equals(XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode(),searchDataInConditionDTO.getBusinessType())){
                searchDataInConditionDTO.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                searchDataInConditionDTO.setAttr(FieldTypeEnum.DATAID.getAlias());
                fieldAttrEntity.setLinkedText(CustomerManagementEnum.NAME.getAttr());
                fieldTypeEnum = FieldTypeEnum.DATAID;
            }else if (Objects.equals(XbbRefTypeEnum.PREPAY_BALANCE.getCode(),searchDataInConditionDTO.getBusinessType())) {
                searchDataInConditionDTO.setBusinessType(XbbRefTypeEnum.SUPPLIER.getCode());
                searchDataInConditionDTO.setAttr(FieldTypeEnum.DATAID.getAlias());
                fieldAttrEntity.setLinkedText(SupplierEnum.SUPPLIER_NAME.getAttr());
                fieldTypeEnum = FieldTypeEnum.DATAID;
            }else if (Objects.equals(XbbRefTypeEnum.CUSTOMER_STATEMENT.getCode(),searchDataInConditionDTO.getBusinessType())) {
                chartQueryHelp.statementQuery4CheckData(boolQueryBuilder, searchDataInConditionDTO.getCheckingDate());
            }else {
                if (searchDataInConditionDTO.getLimitForms()) {
                    boolQueryBuilder.filter(termsQuery("formId", searchDataInConditionDTO.getFormIdList()));
                } else {
                    boolQueryBuilder.filter(termQuery("formId", searchDataInConditionDTO.getFormId()));
                }
            }
            boolQueryBuilder.filter(termQuery("del", searchDataInConditionDTO.getDel()));
            String attr = searchDataInConditionDTO.getAttr();
            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(searchDataInConditionDTO.getCorpid(), searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getSaasMark());

            EsUtil.parseCondition(boolQueryBuilder,searchDataInConditionDTO.getConditionsList(),"",searchDataInConditionDTO.getCorpid(),searchDataInConditionDTO.getBusinessType());
            EsUtil.parseShouldCondition(boolQueryBuilder,searchDataInConditionDTO.getShouldConditionsList(),"",searchDataInConditionDTO.getCorpid(),searchDataInConditionDTO.getBusinessType());
            // 共享权限
            EsUtil.parseSharePermissionCondition(boolQueryBuilder, searchDataInConditionDTO.getSharePermission(), searchDataInConditionDTO.getCorpid(), searchDataInConditionDTO.getBusinessType(), false);
            productCondition(boolQueryBuilder,searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getSubBusinessType(), fieldAttrEntity.getAttr());
            // 模糊查询 类似于sql中的like
            String linkText = fieldAttrEntity.getLinkedText();
            Object conditionValue = searchDataInConditionDTO.getValue();
            String field = "data." + linkText;
            String name = field + ".keyword";
            if (conditionValue != null && StringUtil.isNotEmpty(conditionValue.toString())) {
                QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(field, searchDataInConditionDTO.getValue());
                boolQueryBuilder.filter(queryBuilder);
            }
            boolQueryBuilder.filter(existsQuery(name.replace(".keyword", "")));
            boolQueryBuilder.mustNot(termQuery(name, ""));
            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
            List<IndexBoost> indexBoosts = new ArrayList<>(1);
            indexBoosts.add(new IndexBoost(indexTypeEnum.getIndex(),0));
            nativeSearchQueryBuilder.withIndicesBoost(indexBoosts);
            NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
            TopHitsDTO topHitsDTO = new TopHitsDTO();
            BeanUtil.copyProperties(searchDataInConditionDTO, topHitsDTO);
            topHitsDTO.setSearchQuery(searchQuery);
            String fieldAttr;
            if(Objects.equals(FieldTypeEnum.DATAID.getAlias(),attr)){
                fieldAttr = attr;
            }else{
                fieldAttr = "data." + fieldAttrEntity.getAttr();
            }
            topHitsDTO.setField(fieldAttr);
            topHitsDTO.setFieldTypeEnum(fieldTypeEnum);
            topHitsDTO.setSaasMark(searchDataInConditionDTO.getSaasMark());
            topHitsDTO.setBusinessType(searchDataInConditionDTO.getBusinessType());
            topHitsDTO.setSource(Arrays.asList(fieldAttr,field));
            List<PaasFormDataEntityExt> dataList = esHelper.topHits(topHitsDTO, indexTypeEnum);
            if (dataList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            List<ItemDataPoJo> list = new ArrayList<>();
            for (PaasFormDataEntityExt paasFormDataEsEntity : dataList) {
                JSONObject data = paasFormDataEsEntity.getData();
                Object textObj = data.get(linkText);
                Object valueObj = data.get(fieldAttrEntity.getAttr());
                //fieldType为20002时
                if(textObj instanceof JSONArray && valueObj instanceof JSONArray){
                    JSONArray textArray = (JSONArray)textObj;
                    JSONArray valueArray = (JSONArray)valueObj;
                    for(int i = 0; i < textArray.size(); i++){
                        if (i > valueArray.size()) {
                            break;
                        }
                        ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                        itemDataPoJo.setText(textArray.get(i).toString());
                        itemDataPoJo.setValue(valueArray.get(i));
                        list.add(itemDataPoJo);
                    }
                }else {
                    ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                    itemDataPoJo.setText(data.get(linkText));
                    if(Objects.equals(FieldTypeEnum.DATAID.getAlias(),attr)){
                        itemDataPoJo.setValue(paasFormDataEsEntity.getDataId());
                    }else{
                        itemDataPoJo.setValue(valueObj);
                    }
                    list.add(itemDataPoJo);
                }

            }
            searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        }catch (Exception e){
            LOG.error("distinctData检索文本字段出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return searchDataInConditionVO;
    }

    /**
     * 产品筛选框的下拉值特殊处理
     * @param searchDataInConditionVO
     * @param searchDataInConditionDTO
     * @param fieldTypeEnum
     * @return
     * @throws XbbException
     */
    private SearchDataInConditionVO listOfLinkWarehouse(SearchDataInConditionVO searchDataInConditionVO, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) throws XbbException {
        searchDataInConditionDTO.setBusinessType(XbbRefTypeEnum.WAREHOUSE.getCode());
        searchDataInConditionDTO.setSubBusinessType(XbbRefTypeEnum.WAREHOUSE.getCode());
        searchDataInConditionDTO.setAttr(WarehouseEnum.WAREHOUSE_NAME.getAttr());
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.WAREHOUSE.getCode(), searchDataInConditionDTO.getCorpid());
        if (Objects.isNull(paasFormEntityExt)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        //解析查询条件
        boolQueryBuilder.filter(termQuery("corpid.keyword", searchDataInConditionDTO.getCorpid()));
        boolQueryBuilder.filter(termQuery("appId", paasFormEntityExt.getAppId()));
        if (searchDataInConditionDTO.getLimitForms()) {
            boolQueryBuilder.filter(termsQuery("formId", searchDataInConditionDTO.getFormIdList()));
        } else {
            boolQueryBuilder.filter(termQuery("formId", paasFormEntityExt.getId()));
        }
        boolQueryBuilder.filter(termQuery("del", searchDataInConditionDTO.getDel()));
        EsUtil.parseCondition(boolQueryBuilder,searchDataInConditionDTO.getConditionsList(),"",searchDataInConditionDTO.getCorpid(),XbbRefTypeEnum.WAREHOUSE.getCode());
        EsUtil.parseShouldCondition(boolQueryBuilder,searchDataInConditionDTO.getShouldConditionsList(),"",searchDataInConditionDTO.getCorpid(),XbbRefTypeEnum.WAREHOUSE.getCode());

        UserVO userVO = searchDataInConditionDTO.getLoginUser();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(userVO, userEntity);
        boolean isAdminOrBoss = userVO.isAdminOrBoss();
        Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.SAAS, XbbRefTypeEnum.WAREHOUSE.getCode(), null);
        if (Objects.equals(dataPermission, 5)) {
            isAdminOrBoss = true;
        }
        if (!isAdminOrBoss){
            List<WarehouseUserEntity> warehouseManagerList = warehouseService.getWarehouseManagerList(userVO);
            Set<Long> warehouseIdIn = new HashSet<>();
            warehouseIdIn.add(-1L);
            for (WarehouseUserEntity entity : warehouseManagerList) {
                warehouseIdIn.add(entity.getDataId());
            }
            boolQueryBuilder.filter(termsQuery(FieldTypeEnum.DATAID.getAlias(), warehouseIdIn));
        }
        // 模糊查询 类似于sql中的like
        String attr = WarehouseEnum.WAREHOUSE_NAME.getAttr();
        Object conditionValue = searchDataInConditionDTO.getValue();
        String field = "data." + attr;
        String name = field + ".keyword";
        if (conditionValue != null && StringUtil.isNotEmpty(conditionValue.toString())) {
            QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(field, searchDataInConditionDTO.getValue());
            boolQueryBuilder.filter(queryBuilder);
        }
        boolQueryBuilder.filter(existsQuery(name.replace(".keyword", "")));
        boolQueryBuilder.mustNot(termQuery(name, ""));
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
//        nativeSearchQueryBuilder.withIndices(IndexTypeEnum.getByCode(XbbRefTypeEnum.WAREHOUSE.getCode()).getIndex()).withTypes(IndexTypeEnum.getByCode(XbbRefTypeEnum.WAREHOUSE.getCode()).getType());
        List<IndexBoost> indexBoosts = new ArrayList<>(1);
        indexBoosts.add(new IndexBoost(IndexTypeEnum.IDX_SAAS_WAREHOUSE.getIndex(),0));
        nativeSearchQueryBuilder.withIndicesBoost(indexBoosts);
        NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
        TopHitsDTO topHitsDTO = new TopHitsDTO();
        BeanUtil.copyProperties(searchDataInConditionDTO, topHitsDTO);
        topHitsDTO.setSearchQuery(searchQuery);
        topHitsDTO.setField(field);
        topHitsDTO.setFieldTypeEnum(fieldTypeEnum);
        topHitsDTO.setSaasMark(searchDataInConditionDTO.getSaasMark());
        topHitsDTO.setBusinessType(searchDataInConditionDTO.getBusinessType());
        topHitsDTO.setSource(Arrays.asList("data." + attr,field, FieldTypeEnum.DATAID.getAlias()));
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(searchDataInConditionDTO.getCorpid(), searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getSaasMark());
        List<PaasFormDataEntityExt> dataList = esHelper.topHits(topHitsDTO, indexTypeEnum);

        if (dataList == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        List<ItemDataPoJo> list = new ArrayList<>();
        for (PaasFormDataEntityExt paasFormDataEsEntity : dataList) {
            JSONObject data = paasFormDataEsEntity.getData();
            ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
            Object textObj = data.get(attr);
            Object valueObj = paasFormDataEsEntity.getDataId();

            itemDataPoJo.setText(textObj);
            itemDataPoJo.setValue(Objects.requireNonNull(valueObj).toString());
            list.add(itemDataPoJo);
        }
        if (Objects.equals(searchDataInConditionDTO.getListGroupId(), ListGroupEnum.WARNING_SEARCH.getCode().longValue())) {
            ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
            itemDataPoJo.setText(I18nMessageUtil.getMessage(I18nStringConstant.ALL_WAREHOUSE));
            itemDataPoJo.setValue(0);
            list.add(0,itemDataPoJo);
        }
        searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        return searchDataInConditionVO;
    }

    /**
     * 产品筛选框的供应商下拉值特殊处理
     * @param searchDataInConditionVO
     * @param searchDataInConditionDTO
     * @param fieldTypeEnum
     * @return
     * @throws XbbException
     */
    private SearchDataInConditionVO listOfLinkSupplier(SearchDataInConditionVO searchDataInConditionVO, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) throws XbbException {
        searchDataInConditionDTO.setBusinessType(XbbRefTypeEnum.SUPPLIER.getCode());
        searchDataInConditionDTO.setSubBusinessType(XbbRefTypeEnum.SUPPLIER.getCode());
        searchDataInConditionDTO.setAttr(SupplierEnum.SUPPLIER_NAME.getAttr());
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.SUPPLIER.getCode(), searchDataInConditionDTO.getCorpid());
        if (Objects.isNull(paasFormEntityExt)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        //解析查询条件
        boolQueryBuilder.filter(termQuery("corpid.keyword", searchDataInConditionDTO.getCorpid()));
        boolQueryBuilder.filter(termQuery("appId", paasFormEntityExt.getAppId()));
        if (searchDataInConditionDTO.getLimitForms()) {
            boolQueryBuilder.filter(termsQuery("formId", searchDataInConditionDTO.getFormIdList()));
        } else {
            boolQueryBuilder.filter(termQuery("formId", paasFormEntityExt.getId()));
        }
        boolQueryBuilder.filter(termQuery("del", searchDataInConditionDTO.getDel()));
        boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
        UserEntity userEntity = new UserEntity();
        UserVO userVO = searchDataInConditionDTO.getLoginUser();
        BeanUtil.copyProperties(userVO,userEntity);
        boolean isAdminOrBoss = userVO.isAdminOrBoss();
        Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.SAAS, XbbRefTypeEnum.SUPPLIER.getCode(), null);
        if (Objects.equals(dataPermission, 5)) {
            isAdminOrBoss = true;
        }
        if (!isAdminOrBoss){
            List<String> userIdIn = userModel.getSubIdListByDataPermission(dataPermission, searchDataInConditionDTO.getUserId(), searchDataInConditionDTO.getCorpid(), BasicConstant.ZERO,false);
            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
            conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
            conditionsEntityExt.setValue(new ArrayList<>(userIdIn));
            conditionsEntityExt.setAttr(FieldTypeEnum.OWNERID.getAlias());
            conditionsEntityExt.setFieldType(FieldTypeEnum.OWNERID.getType());
            searchDataInConditionDTO.getConditionsList().add(conditionsEntityExt);
        }
//        EsUtil.parseCondition(boolQueryBuilder,searchDataInConditionDTO.getConditionsList(),"",searchDataInConditionDTO.getCorpid(),XbbRefTypeEnum.SUPPLIER.getCode());
        EsUtil.parseShouldCondition(boolQueryBuilder,searchDataInConditionDTO.getShouldConditionsList(),"",searchDataInConditionDTO.getCorpid(),XbbRefTypeEnum.SUPPLIER.getCode());
        // 模糊查询 类似于sql中的like
        String attr = SupplierEnum.SUPPLIER_NAME.getAttr();
        Object conditionValue = searchDataInConditionDTO.getValue();
        String field = "data." + attr;
        String name = field + ".keyword";
        if (conditionValue != null && StringUtil.isNotEmpty(conditionValue.toString())) {
            QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(field, searchDataInConditionDTO.getValue());
            boolQueryBuilder.filter(queryBuilder);
        }
        boolQueryBuilder.filter(existsQuery(name.replace(".keyword", "")));
        boolQueryBuilder.mustNot(termQuery(name, ""));
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
//        nativeSearchQueryBuilder.withIndices(IndexTypeEnum.getByCode(XbbRefTypeEnum.SUPPLIER.getCode()).getIndex()).withTypes(IndexTypeEnum.getByCode(XbbRefTypeEnum.SUPPLIER.getCode()).getType());
        List<IndexBoost> indexBoosts = new ArrayList<>(1);
        indexBoosts.add(new IndexBoost(IndexTypeEnum.IDX_SAAS_SUPPLIER.getIndex(),0));
        nativeSearchQueryBuilder.withIndicesBoost(indexBoosts);
        NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
        TopHitsDTO topHitsDTO = new TopHitsDTO();
        BeanUtil.copyProperties(searchDataInConditionDTO, topHitsDTO);
        topHitsDTO.setSearchQuery(searchQuery);
        topHitsDTO.setField(field);
        topHitsDTO.setFieldTypeEnum(fieldTypeEnum);
        topHitsDTO.setSaasMark(searchDataInConditionDTO.getSaasMark());
        topHitsDTO.setBusinessType(searchDataInConditionDTO.getBusinessType());
        topHitsDTO.setSource(Arrays.asList("data." + attr,field, FieldTypeEnum.DATAID.getAlias()));
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(searchDataInConditionDTO.getCorpid(), searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getSaasMark());
        List<PaasFormDataEntityExt> dataList = esHelper.topHits(topHitsDTO, indexTypeEnum);

        if (dataList == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        List<ItemDataPoJo> list = new ArrayList<>();
        for (PaasFormDataEntityExt paasFormDataEsEntity : dataList) {
            JSONObject data = paasFormDataEsEntity.getData();
            ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
            Object textObj = data.get(attr);
            Object valueObj = paasFormDataEsEntity.getDataId();

            itemDataPoJo.setText(textObj);
            itemDataPoJo.setValue(Objects.requireNonNull(valueObj).toString());
            list.add(itemDataPoJo);
        }
        searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        return searchDataInConditionVO;
    }

    /**
     * 暂时是用来检索跟进记录中的客户
     * @param fieldAttrEntity
     * @param searchDataInConditionVO
     * @param searchDataInConditionDTO
     * @return
     * @throws XbbException
     */
    private SearchDataInConditionVO listOfLinkCustomer(FieldAttrEntity fieldAttrEntity, SearchDataInConditionVO searchDataInConditionVO, SearchDataInConditionDTO searchDataInConditionDTO) throws XbbException {
        Integer businessType = fieldAttrEntity.getLinkedType();

        BoolQueryBuilder boolQueryBuilder = boolQuery();
        //解析查询条件
        boolQueryBuilder.filter(termQuery("corpid.keyword", searchDataInConditionDTO.getCorpid()));
        boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
        Map<String, Object> formParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Integer distributorMark = searchDataInConditionDTO.getDistributorMark() == null ? 0 : searchDataInConditionDTO.getDistributorMark();
        formParam.put("del", DelEnum.NORMAL.getDel());
        formParam.put("corpid", searchDataInConditionDTO.getCorpid());
        formParam.put("businessType", XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
        List<PaasFormEntityExt> forms = paasFormModel.findEntitys(formParam);
        List<Long> formIdList = new ArrayList<>();
        forms.forEach(item -> {
            if (Objects.equals(distributorMark, item.getDistributorMark())) {
                formIdList.add(item.getId());
            }
        });
        boolQueryBuilder.filter(termsQuery("formId", formIdList));
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(searchDataInConditionDTO.getCorpid(), businessType, SaasMarkEnum.SAAS.getCode());
        EsUtil.parseCondition(boolQueryBuilder,searchDataInConditionDTO.getConditionsList(),"",searchDataInConditionDTO.getCorpid(), businessType);
        EsUtil.parseShouldCondition(boolQueryBuilder,searchDataInConditionDTO.getShouldConditionsList(),"",searchDataInConditionDTO.getCorpid(), businessType);
        // 模糊查询 类似于sql中的like
        // TODO 后续增加的话，需要搞个枚举，业务和字段去对应
        String attr = CustomerManagementEnum.NAME.getAttr();
        Object conditionValue = searchDataInConditionDTO.getValue();
        String field = "data." + attr;
        String name = field + ".keyword";
        if (conditionValue != null && StringUtil.isNotEmpty(conditionValue.toString())) {
            QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(field, searchDataInConditionDTO.getValue());
            boolQueryBuilder.filter(queryBuilder);
        }

        boolQueryBuilder.filter(existsQuery(field));
        boolQueryBuilder.mustNot(termQuery(name, ""));
        // 检索的字段
        List<String> source = new ArrayList<>();
        source.add(attr);

        List<PaasFormDataEntityExt> dataList = paasEsModel.getDataList(boolQueryBuilder, indexTypeEnum,source, 1, 10, PaasFormDataEntityExt.class,
                FieldTypeEnum.UPDATETIME.getAlias(), SortOrder.DESC);

        if (dataList == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        List<ItemDataPoJo> list = new ArrayList<>();
        for (PaasFormDataEntityExt paasFormDataEsEntity : dataList) {
            JSONObject data = paasFormDataEsEntity.getData();
            ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
            Object textObj = data.get(attr);
            Object valueObj = paasFormDataEsEntity.getDataId();
            itemDataPoJo.setText(textObj);
            itemDataPoJo.setValue(Objects.requireNonNull(valueObj).toString());
            list.add(itemDataPoJo);
        }
        searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        return searchDataInConditionVO;
    }

    @Override
    public SearchDataInConditionVO listOfSelectProduct(FieldAttrEntity fieldAttrEntity, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) throws XbbException{
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        try {
            PaasFormEntity paasFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(),searchDataInConditionDTO.getCorpid());
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            //解析查询条件
            boolQueryBuilder.filter(termQuery("corpid.keyword", searchDataInConditionDTO.getCorpid()));
            boolQueryBuilder.filter(termQuery("appId", paasFormEntity.getAppId()));
            boolQueryBuilder.filter(termQuery("formId", paasFormEntity.getId()));
            boolQueryBuilder.filter(termQuery("del", searchDataInConditionDTO.getDel()));
            boolQueryBuilder.mustNot(termQuery("data." + ProductEnum.PARENT_ID.getAttr(),0));
            boolQueryBuilder.filter(termQuery("data." + ProductEnum.ENABLE_SKU.getAttr(),1));
//            EsUtil.parseCondition(boolQueryBuilder,searchDataInConditionDTO.getConditionsList(),"",searchDataInConditionDTO.getCorpid(),searchDataInConditionDTO.getBusinessType());
//            EsUtil.parseShouldCondition(boolQueryBuilder,searchDataInConditionDTO.getShouldConditionsList(),"",searchDataInConditionDTO.getCorpid(),searchDataInConditionDTO.getBusinessType());
//            productCondition(boolQueryBuilder,searchDataInConditionDTO.getBusinessType());
            // 模糊查询 类似于sql中的like
            String attr = ProductEnum.NAME.getAttr();
            Object conditionValue = searchDataInConditionDTO.getValue();
            String field = "data." + attr;
            if (conditionValue != null && StringUtil.isNotEmpty(conditionValue.toString())) {
                QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(field, searchDataInConditionDTO.getValue());
                boolQueryBuilder.filter(queryBuilder);
            }
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_PRODUCT.getType()));
            sourceBuilder.query(boolQueryBuilder);
            sourceBuilder.sort((new FieldSortBuilder(ProductEnum.getAttrConnectData(ProductEnum.NAME) + ".raw").order(SortOrder.ASC)));
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PRODUCT.getIndex());
            searchRequest.source(sourceBuilder);
            PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, 10);
            XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest,searchRequest,PaasFormDataEntityExt.class);
            List<PaasFormDataEntityExt> dataList = esEntities.getContent();
            if (dataList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            List<ItemDataPoJo> list = new ArrayList<>();
            for (PaasFormDataEntityExt paasFormDataEsEntity : dataList) {
                JSONObject data = paasFormDataEsEntity.getData();
                ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                String productName = data.getString(ProductEnum.NAME.getAttr());
                String productNo = paasFormDataEsEntity.getSerialNo();
                String specification = "";
                if (Objects.equals(data.getInteger(ProductEnum.SPECIFICATION.getAttr()),1)){
                    JSONObject specifition;
                    try {
                        specifition = JSONObject.parseObject(data.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr()));
                    }catch (Exception e){
                        specifition = new JSONObject();
                    }
                    StringBuilder stringBuilder = new StringBuilder();
                    if (!Objects.isNull(specifition)){
                        for (Map.Entry entry : specifition.entrySet()){
                            StringUtil.stringBuilderAppendSuffix(stringBuilder,"/",entry.getValue());
                        }
                    }
                    specification = stringBuilder.toString();
                }else {
                    specification = data.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr());
                }
                String text = "";
                if (StringUtil.isNotEmpty(productName)){
                    text = productName + " ";
                }
                if (StringUtil.isNotEmpty(productNo)){
                    text = text + productNo + " ";
                }
                if (StringUtil.isNotEmpty(specification)){
                    text = text + specification;
                }
                itemDataPoJo.setText(text);
//                List<Long> childIdList = childIdMap.getOrDefault(paasFormDataEsEntity.getDataId(),new ArrayList<>());
                itemDataPoJo.setValue(paasFormDataEsEntity.getDataId());
                list.add(itemDataPoJo);

            }
            searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        }catch (Exception e){
            LOG.error("distinctData检索文本字段出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return searchDataInConditionVO;
    }

    @Override
    public SearchDataInConditionVO listOfSelectPurchase(FieldAttrEntity fieldAttrEntity, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) throws XbbException{
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        try {
            PaasFormEntity paasFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.PURCHASE.getCode(),searchDataInConditionDTO.getCorpid());
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            //解析查询条件
            boolQueryBuilder.filter(termQuery("corpid.keyword", searchDataInConditionDTO.getCorpid()));
            boolQueryBuilder.filter(termQuery("appId", paasFormEntity.getAppId()));
            boolQueryBuilder.filter(termQuery("formId", paasFormEntity.getId()));
            boolQueryBuilder.filter(termQuery("del", searchDataInConditionDTO.getDel()));
            String attr = PurchaseEnum.PURCHASE_NAME.getAttr();
            Object conditionValue = searchDataInConditionDTO.getValue();
            String field = "data." + attr;
            if (conditionValue != null && StringUtil.isNotEmpty(conditionValue.toString())) {
                QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(field, searchDataInConditionDTO.getValue());
                boolQueryBuilder.filter(queryBuilder);
            }
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_PURCHASE.getType()));
            sourceBuilder.query(boolQueryBuilder);
            sourceBuilder.sort((new FieldSortBuilder(ProductEnum.getAttrConnectData(ProductEnum.NAME) + ".raw").order(SortOrder.ASC)));
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PURCHASE.getIndex());
            searchRequest.source(sourceBuilder);
            PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, 10);
            XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest,searchRequest,PaasFormDataEntityExt.class);
            List<PaasFormDataEntityExt> dataList = esEntities.getContent();
            if (dataList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            List<ItemDataPoJo> list = new ArrayList<>();
            for (PaasFormDataEntityExt paasFormDataEsEntity : dataList) {
                JSONObject data = paasFormDataEsEntity.getData();
                ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                String purchaseName = data.getString(PurchaseEnum.PURCHASE_NAME.getAttr());
                String purchaseNo = paasFormDataEsEntity.getSerialNo();
                String text = "";
                if (StringUtil.isNotEmpty(purchaseName)){
                    text = purchaseName + " ";
                }
                if (StringUtil.isNotEmpty(purchaseNo)){
                    text = text + purchaseNo + " ";
                }
                itemDataPoJo.setText(text);
                itemDataPoJo.setValue(paasFormDataEsEntity.getDataId());
                list.add(itemDataPoJo);
            }
            searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        }catch (Exception e){
            LOG.error("distinctData检索文本字段出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return searchDataInConditionVO;
    }

    @Override
    public SearchDataInConditionVO listOfSelectContract(FieldAttrEntity fieldAttrEntity, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) throws XbbException{
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        try {
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            //解析查询条件
            boolQueryBuilder.filter(termQuery("corpid.keyword", searchDataInConditionDTO.getCorpid()));
            boolQueryBuilder.filter(termQuery("appId", searchDataInConditionDTO.getAppId()));
            if (Objects.equals(XbbRefTypeEnum.CONTRACT.getCode(),searchDataInConditionDTO.getBusinessType()) && Objects.equals(XbbRefTypeEnum.WAIT_PURCHASE.getCode(),searchDataInConditionDTO.getSubBusinessType())){
                boolQueryBuilder.filter(termsQuery("formId", searchDataInConditionDTO.getFormIdList()));
            }else {
                boolQueryBuilder.filter(termQuery("formId", searchDataInConditionDTO.getFormId()));
            }
            boolQueryBuilder.filter(termQuery("del", searchDataInConditionDTO.getDel()));
            String attr = ContractEnum.NAME.getAttr();
            Object conditionValue = searchDataInConditionDTO.getValue();
            String field = "data." + attr;
            if (conditionValue != null && StringUtil.isNotEmpty(conditionValue.toString())) {
                QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(field, searchDataInConditionDTO.getValue());
                boolQueryBuilder.filter(queryBuilder);
            }
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_CONTRACT.getType()));
            sourceBuilder.query(boolQueryBuilder);
            sourceBuilder.sort(new FieldSortBuilder("addTime").order(SortOrder.DESC));
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CONTRACT.getIndex());
            searchRequest.source(sourceBuilder);
            PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, 10);
            XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest,searchRequest,PaasFormDataEntityExt.class);
            List<PaasFormDataEntityExt> dataList = esEntities.getContent();
            if (dataList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }

            List<ItemDataPoJo> list = new ArrayList<>();
            for (PaasFormDataEntityExt paasFormDataEsEntity : dataList) {
                JSONObject data = paasFormDataEsEntity.getData();
                ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                String contractName = data.getString(ContractEnum.NAME.getAttr());
                String contractNo = paasFormDataEsEntity.getSerialNo();
                String text = "";
                if (StringUtil.isNotEmpty(contractName)){
                    text = contractName + " ";
                }
                if (StringUtil.isNotEmpty(contractNo)){
                    text = text + contractNo + " ";
                }
                itemDataPoJo.setText(text);
                itemDataPoJo.setValue(paasFormDataEsEntity.getDataId());
                list.add(itemDataPoJo);
            }
            searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        }catch (Exception e){
            LOG.error("distinctData检索文本字段出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return searchDataInConditionVO;
    }
    @Override
    public SearchDataInConditionVO listOfSelectSerialNo(FieldAttrEntity fieldAttrEntity, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) throws XbbException{
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        try {
            PaasFormEntity paasFormEntity = new PaasFormEntity();
            Long formId = searchDataInConditionDTO.getFormId();
            String corpid = searchDataInConditionDTO.getCorpid();
            if (Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())) {
                //工单
                WorkOrderFormEntity workOrderFormEntity;
                if (Objects.equals(formId, 0L)) {
                    workOrderFormEntity = workOrderFormModel.getByKey(searchDataInConditionDTO.getFormIdList().get(0), corpid);
                } else {
                    workOrderFormEntity = workOrderFormModel.getByKey(formId, corpid);
                }
                BeanUtil.copyProperties(workOrderFormEntity, paasFormEntity);
            } else if (Objects.equals(SaasMarkEnum.SAAS.getCode(), searchDataInConditionDTO.getSaasMark())) {
                if (Objects.nonNull(searchDataInConditionDTO.getFormId())){
                    paasFormEntity = paasFormModel.getByKey(formId,searchDataInConditionDTO.getCorpid());
                }else {
                    paasFormEntity = paasFormModel.getByBusinessType(searchDataInConditionDTO.getBusinessType(),corpid);
                }
            } else {
                paasFormEntity = paasFormModel.getByKey(formId,searchDataInConditionDTO.getCorpid());
            }
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            //解析查询条件
            boolQueryBuilder.filter(termQuery("corpid.keyword", searchDataInConditionDTO.getCorpid()));
//            boolQueryBuilder.filter(termQuery("appId", paasFormEntity.getAppId()));
            if (searchDataInConditionDTO.getLimitForms()){
                boolQueryBuilder.filter(termsQuery("formId", searchDataInConditionDTO.getFormIdList()));
            } else {
                boolQueryBuilder.filter(termQuery("formId", paasFormEntity.getId()));
            }
            boolQueryBuilder.filter(termQuery("del", searchDataInConditionDTO.getDel()));
            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(searchDataInConditionDTO.getCorpid(), searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getSaasMark());

            EsUtil.parseCondition(boolQueryBuilder,searchDataInConditionDTO.getConditionsList(),"",corpid,searchDataInConditionDTO.getBusinessType());
            EsUtil.parseShouldCondition(boolQueryBuilder,searchDataInConditionDTO.getShouldConditionsList(),"",corpid,searchDataInConditionDTO.getBusinessType());
            // 共享权限
            EsUtil.parseSharePermissionCondition(boolQueryBuilder, searchDataInConditionDTO.getSharePermission(), corpid, searchDataInConditionDTO.getBusinessType(), false);
            productCondition(boolQueryBuilder,searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getSubBusinessType(), fieldAttrEntity.getAttr());
            // 模糊查询 类似于sql中的like
            String attr = FieldTypeEnum.SERIALNO.getAlias();
            Object conditionValue = searchDataInConditionDTO.getValue();
            if (conditionValue != null && StringUtil.isNotEmpty(conditionValue.toString())) {
                QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(attr, searchDataInConditionDTO.getValue());
                boolQueryBuilder.filter(queryBuilder);
            }
            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
            NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
            TopHitsDTO topHitsDTO = new TopHitsDTO();
            BeanUtil.copyProperties(searchDataInConditionDTO, topHitsDTO);
            topHitsDTO.setSearchQuery(searchQuery);
            topHitsDTO.setField(attr);
            topHitsDTO.setFieldTypeEnum(fieldTypeEnum);
            topHitsDTO.setSaasMark(searchDataInConditionDTO.getSaasMark());
            topHitsDTO.setBusinessType(searchDataInConditionDTO.getBusinessType());
            List<PaasFormDataEntityExt> dataList = esHelper.topHits(topHitsDTO, indexTypeEnum);
            if (dataList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            List<ItemDataPoJo> list = new ArrayList<>();
            for (PaasFormDataEntityExt paasFormDataEsEntity : dataList) {
                ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                itemDataPoJo.setText(paasFormDataEsEntity.getSerialNo());
                itemDataPoJo.setValue(paasFormDataEsEntity.getSerialNo());
                list.add(itemDataPoJo);

            }
            searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        }catch (Exception e){
            LOG.error("distinctData检索文本字段出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return searchDataInConditionVO;
    }

    @Override
    public SearchDataInConditionVO listOfStar(FieldAttrEntity fieldAttrEntity, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) {
        List<ItemDataPoJo> list = new ArrayList<>();
        list.add(new ItemDataPoJo(I18nMessageUtil.getMessage(CommonConstant.LESS_THAN_ONE_STAR),0));
        list.add(new ItemDataPoJo(I18nMessageUtil.getMessage(CommonConstant.ONE_STAR),1));
        list.add(new ItemDataPoJo(I18nMessageUtil.getMessage(CommonConstant.TWO_STAR),2));
        list.add(new ItemDataPoJo(I18nMessageUtil.getMessage(CommonConstant.THREE_STAR),3));
        list.add(new ItemDataPoJo(I18nMessageUtil.getMessage(CommonConstant.FOUR_STAR),4));
        list.add(new ItemDataPoJo(I18nMessageUtil.getMessage(CommonConstant.FIVE_STAR),5));
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        return searchDataInConditionVO;
    }

    @Override
    public SearchDataInConditionVO listOfWorkOrderOut(FieldAttrEntity fieldAttrEntity, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) {
        List<ItemDataPoJo> list = new ArrayList<>();
        list.add(new ItemDataPoJo(I18nMessageUtil.getMessage(I18nStringConstant.TIMED_OUT),"0"));
        list.add(new ItemDataPoJo(I18nMessageUtil.getMessage(I18nStringConstant.NOT_TIMED_OUT),"1"));
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        return searchDataInConditionVO;
    }

    @Override
    public SearchDataInConditionVO listOfWorkOrderStatus(FieldAttrEntity fieldAttrEntity, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) {
        List<ItemDataPoJo> list = new ArrayList<>();
        if (Objects.equals(searchDataInConditionDTO.getDefaultGroup(),1) && (Objects.equals(searchDataInConditionDTO.getListGroupId(),(long)ListGroupEnum.WORK_ORDER_RESPONSE_BY_ME.getCode()) || Objects.equals(searchDataInConditionDTO.getListGroupId(),(long)ListGroupEnum.WORK_ORDER_RESPONSE_BY_SUB.getCode()))){
            list.add(new ItemDataPoJo(WorkOrderNodeStatusEnum.UNACCEPTED.getName(),WorkOrderNodeStatusEnum.UNACCEPTED.getCode()));
            list.add(new ItemDataPoJo(WorkOrderNodeStatusEnum.ONGOING.getName(),WorkOrderNodeStatusEnum.ONGOING.getCode()));
            list.add(new ItemDataPoJo(WorkOrderNodeStatusEnum.FINISH.getName(),WorkOrderNodeStatusEnum.FINISH.getCode()));
            list.add(new ItemDataPoJo(WorkOrderNodeStatusEnum.CLOSE.getName(),WorkOrderNodeStatusEnum.CLOSE.getCode()));
            list.add(new ItemDataPoJo(WorkOrderNodeStatusEnum.ROLLBACK.getName(),WorkOrderNodeStatusEnum.ROLLBACK.getCode()));
            list.add(new ItemDataPoJo(WorkOrderNodeStatusEnum.TRANSFERRED.getName(),WorkOrderNodeStatusEnum.TRANSFERRED.getCode()));
        }else {
            list.add(new ItemDataPoJo(WorkOrderStatusEnum.UNACCEPTED.getName(),WorkOrderStatusEnum.UNACCEPTED.getCode()));
            list.add(new ItemDataPoJo(WorkOrderStatusEnum.ONGOING.getName(),WorkOrderStatusEnum.ONGOING.getCode()));
            list.add(new ItemDataPoJo(WorkOrderStatusEnum.FINISH.getName(),WorkOrderStatusEnum.FINISH.getCode()));
            list.add(new ItemDataPoJo(WorkOrderStatusEnum.CLOSE.getName(),WorkOrderStatusEnum.CLOSE.getCode()));
        }
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        return searchDataInConditionVO;
    }

    @Override
    public SearchDataInConditionVO listOfAddress(FieldAttrEntity fieldAttrEntity, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) throws XbbException{
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        try {
            PaasFormEntity paasFormEntity = new PaasFormEntity();
            if (Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())) {
                //工单
                WorkOrderFormEntity workOrderFormEntity = workOrderFormModel.getByKey(searchDataInConditionDTO.getFormId(), searchDataInConditionDTO.getCorpid());
                BeanUtil.copyProperties(workOrderFormEntity, paasFormEntity);
            } else {
                paasFormEntity = paasFormModel.getByBusinessType(searchDataInConditionDTO.getBusinessType(),searchDataInConditionDTO.getCorpid());
            }
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            //解析查询条件
            boolQueryBuilder.filter(termQuery("corpid.keyword", searchDataInConditionDTO.getCorpid()));
            boolQueryBuilder.filter(termQuery("appId", paasFormEntity.getAppId()));
            boolQueryBuilder.filter(termQuery("formId", paasFormEntity.getId()));
            boolQueryBuilder.filter(termQuery("del", searchDataInConditionDTO.getDel()));
            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(searchDataInConditionDTO.getCorpid(), searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getSaasMark());

            EsUtil.parseCondition(boolQueryBuilder,searchDataInConditionDTO.getConditionsList(),"",searchDataInConditionDTO.getCorpid(),searchDataInConditionDTO.getBusinessType());
            EsUtil.parseShouldCondition(boolQueryBuilder,searchDataInConditionDTO.getShouldConditionsList(),"",searchDataInConditionDTO.getCorpid(),searchDataInConditionDTO.getBusinessType());
            // 共享权限
            EsUtil.parseSharePermissionCondition(boolQueryBuilder, searchDataInConditionDTO.getSharePermission(), searchDataInConditionDTO.getCorpid(), searchDataInConditionDTO.getBusinessType(), false);
            productCondition(boolQueryBuilder,searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getSubBusinessType(), fieldAttrEntity.getAttr());
            String attr = searchDataInConditionDTO.getAttr();
            String field = "data." + attr;
            String subAttr = searchDataInConditionDTO.getSubAttr();
            boolQueryBuilder.mustNot(termQuery(field + "." + subAttr + ".keyword",""));
//            String[] attrList = attr.split(",");
//            String address = attrList[1];
            Object conditionValue = searchDataInConditionDTO.getValue();
            if (conditionValue != null && StringUtil.isNotEmpty(conditionValue.toString())) {
                QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(field + "." + subAttr, searchDataInConditionDTO.getValue());
                boolQueryBuilder.filter(queryBuilder);
            }
            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
            NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
            TopHitsDTO topHitsDTO = new TopHitsDTO();
            BeanUtil.copyProperties(searchDataInConditionDTO, topHitsDTO);
            topHitsDTO.setSearchQuery(searchQuery);
            topHitsDTO.setField(field);
            topHitsDTO.setFieldTypeEnum(fieldTypeEnum);
            topHitsDTO.setSaasMark(searchDataInConditionDTO.getSaasMark());
            topHitsDTO.setBusinessType(searchDataInConditionDTO.getBusinessType());
            List<PaasFormDataEntityExt> dataList = esHelper.topHits(topHitsDTO, indexTypeEnum);
            if (dataList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            List<ItemDataPoJo> list = new ArrayList<>();
            for (PaasFormDataEntityExt paasFormDataEsEntity : dataList) {
                ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                JSONObject address = paasFormDataEsEntity.getData().getJSONObject(attr);
                String value = (address.getString(subAttr));
                if (Objects.isNull(value)){
                    continue;
                }
                itemDataPoJo.setText(value);
                itemDataPoJo.setValue(value);
                list.add(itemDataPoJo);
            }
            searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        }catch (Exception e){
            LOG.error("distinctData检索文本字段出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return searchDataInConditionVO;
    }

    @Override
    public SearchDataInConditionVO listOfWorkOrderStage(FieldAttrEntity fieldAttrEntity, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) {
        WorkOrderTemplateEntity workOrderTemplateEntity = workOrderTemplateService.getByFormId(searchDataInConditionDTO.getFormId(),searchDataInConditionDTO.getCorpid());
        Long templateId = workOrderTemplateEntity.getId();
        List<WorkOrderStageEntity> workOrderStageEntityList = workOrderStageService.getStageList(templateId,searchDataInConditionDTO.getCorpid(),false);
        List<ItemDataPoJo> list = new ArrayList<>();
        for (WorkOrderStageEntity entity : workOrderStageEntityList){
            ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
            itemDataPoJo.setText(entity.getName());
            itemDataPoJo.setValue(entity.getId());
            list.add(itemDataPoJo);
        }
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        return searchDataInConditionVO;
    }

    @Override
    public SearchDataInConditionVO listOfWorkOrderNodeStatus(FieldAttrEntity fieldAttrEntity, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) {
        List<ItemDataPoJo> list = new ArrayList<>();
        list.add(new ItemDataPoJo(WorkOrderNodeStatusEnum.UNACCEPTED.getName(),"1"));
        list.add(new ItemDataPoJo(WorkOrderNodeStatusEnum.ONGOING.getName(),"2"));
        list.add(new ItemDataPoJo(WorkOrderNodeStatusEnum.FINISH.getName(),"3"));
        list.add(new ItemDataPoJo(WorkOrderNodeStatusEnum.CLOSE.getName(),"4"));
        list.add(new ItemDataPoJo(WorkOrderNodeStatusEnum.ROLLBACK.getName(),"5"));
        list.add(new ItemDataPoJo(WorkOrderNodeStatusEnum.TRANSFERRED.getName(),"6"));
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        return searchDataInConditionVO;
    }

    @Override
    public SearchDataInConditionVO listOfBirthday() {
        List<ItemDataPoJo> list = new ArrayList<>();
        list.add(new ItemDataPoJo(BirthdayFilterEnum.TODAY.getText(),BirthdayFilterEnum.TODAY.getValue()));
        list.add(new ItemDataPoJo(BirthdayFilterEnum.TOMORROW.getText(),BirthdayFilterEnum.TOMORROW.getValue()));
        list.add(new ItemDataPoJo(BirthdayFilterEnum.SEVEN_DAYS.getText(),BirthdayFilterEnum.SEVEN_DAYS.getValue()));
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        return searchDataInConditionVO;
    }

    @Override
    public SearchDataInConditionVO listOfRefId(FieldAttrEntity fieldAttrEntity, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) throws XbbException{
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        try {
            String corpid = searchDataInConditionDTO.getCorpid();
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            //解析查询条件
            boolQueryBuilder.filter(termQuery("corpid.keyword", searchDataInConditionDTO.getCorpid()));
            boolQueryBuilder.filter(termQuery("del", searchDataInConditionDTO.getDel()));
            EsUtil.parseCondition(boolQueryBuilder,searchDataInConditionDTO.getConditionsList(),"",corpid,searchDataInConditionDTO.getBusinessType());
            EsUtil.parseShouldCondition(boolQueryBuilder,searchDataInConditionDTO.getShouldConditionsList(),"",corpid,searchDataInConditionDTO.getBusinessType());
            // 共享权限
            EsUtil.parseSharePermissionCondition(boolQueryBuilder, searchDataInConditionDTO.getSharePermission(), searchDataInConditionDTO.getCorpid(), searchDataInConditionDTO.getBusinessType(), false);
            productCondition(boolQueryBuilder,searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getSubBusinessType(), fieldAttrEntity.getAttr());
            // 模糊查询 类似于sql中的like
            String attr = FieldTypeEnum.SERIALNO.getAlias();
            Object conditionValue = searchDataInConditionDTO.getValue();
            if (conditionValue != null && StringUtil.isNotEmpty(conditionValue.toString())) {
                QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(attr, searchDataInConditionDTO.getValue());
                boolQueryBuilder.filter(queryBuilder);
            }
            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
            NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
            TopHitsDTO topHitsDTO = new TopHitsDTO();
            BeanUtil.copyProperties(searchDataInConditionDTO, topHitsDTO);
            topHitsDTO.setSearchQuery(searchQuery);
            topHitsDTO.setField(attr + ".keyword");
            topHitsDTO.setFieldTypeEnum(fieldTypeEnum);
            topHitsDTO.setSaasMark(searchDataInConditionDTO.getSaasMark());
            topHitsDTO.setBusinessType(searchDataInConditionDTO.getBusinessType());
            topHitsDTO.setSource(Arrays.asList(attr));
            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(searchDataInConditionDTO.getCorpid(), searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getSaasMark());
            List<PaasFormDataEntityExt> dataList = esHelper.topHits(topHitsDTO, indexTypeEnum);
            if (dataList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            List<ItemDataPoJo> list = new ArrayList<>();
            for (PaasFormDataEntityExt paasFormDataEsEntity : dataList) {
                ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                itemDataPoJo.setText(paasFormDataEsEntity.getSerialNo());
                itemDataPoJo.setValue(paasFormDataEsEntity.getDataId());
                list.add(itemDataPoJo);
            }
            searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        }catch (Exception e){
            LOG.error("distinctData检索文本字段出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return searchDataInConditionVO;
    }

    @Override
    public SearchDataInConditionVO listOfBusinessId(FieldAttrEntity fieldAttrEntity, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) throws XbbException {
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        try {
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            //解析查询条件
            boolQueryBuilder.filter(termQuery("corpid.keyword", searchDataInConditionDTO.getCorpid()));
            boolQueryBuilder.filter(termQuery("del", searchDataInConditionDTO.getDel()));
            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(searchDataInConditionDTO.getCorpid(), searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getSaasMark());

            EsUtil.parseCondition(boolQueryBuilder,searchDataInConditionDTO.getConditionsList(),"",searchDataInConditionDTO.getCorpid(),searchDataInConditionDTO.getBusinessType());
            EsUtil.parseShouldCondition(boolQueryBuilder,searchDataInConditionDTO.getShouldConditionsList(),"",searchDataInConditionDTO.getCorpid(),searchDataInConditionDTO.getBusinessType());
            // 共享权限
            EsUtil.parseSharePermissionCondition(boolQueryBuilder, searchDataInConditionDTO.getSharePermission(), searchDataInConditionDTO.getCorpid(), searchDataInConditionDTO.getBusinessType(), false);
            productCondition(boolQueryBuilder,searchDataInConditionDTO.getBusinessType(),searchDataInConditionDTO.getSubBusinessType(),fieldAttrEntity.getAttr());
            String attr = searchDataInConditionDTO.getAttr();
            // 模糊查询 类似于sql中的like
            Object conditionValue = searchDataInConditionDTO.getValue();
            if(conditionValue != null && StringUtil.isNotEmpty(conditionValue.toString())){
                String name = "data."+ attr;
                QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(name, searchDataInConditionDTO.getValue());
                boolQueryBuilder.filter(queryBuilder);
            }
            String field = "data."+attr;
            String name = "";
            if(FieldTypeEnum.TEXT.getEsalias().equals(attr.split(UNDERLINE)[0]) || FieldTypeEnum.SERIALNO.getAlias().equals(attr)){
                name = field + ".keyword";
            }
            boolQueryBuilder.filter(existsQuery(name.replace(".keyword", "")));
            boolQueryBuilder.mustNot(termQuery(name, ""));
            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
            NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
            TopHitsDTO topHitsDTO = new TopHitsDTO();
            BeanUtil.copyProperties(searchDataInConditionDTO, topHitsDTO);
            topHitsDTO.setSearchQuery(searchQuery);
            topHitsDTO.setField(name) ;
            topHitsDTO.setFieldTypeEnum(fieldTypeEnum);
            topHitsDTO.setSaasMark(searchDataInConditionDTO.getSaasMark());
            topHitsDTO.setBusinessType(searchDataInConditionDTO.getBusinessType());
            topHitsDTO.setSource(Arrays.asList(field));
            List<PaasFormDataEntityExt> dataList = esHelper.topHits(topHitsDTO, indexTypeEnum);
            if (dataList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            List<ItemDataPoJo> list = new ArrayList<>();
            for (PaasFormDataEntityExt paasFormDataEsEntity: dataList) {
                JSONObject data = paasFormDataEsEntity.getData();
                Iterator iterator = data.keySet().iterator();
                while (iterator.hasNext()){
                    ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                    String key = iterator.next().toString();
                    if (key.equals(searchDataInConditionDTO.getAttr())) {
                        Object value = data.get(key);
                        Object text = ItemUtil.getText(value, fieldAttrEntity);
                        if (Objects.isNull(text)) {
                            continue;
                        }
                        itemDataPoJo.setText(text);
                        itemDataPoJo.setValue(paasFormDataEsEntity.getDataId());
                        list.add(itemDataPoJo);
                    }
                }
            }
            searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        } catch (Exception e) {
            LOG.error("distinctData检索文本字段出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return searchDataInConditionVO;
    }

    /**
     * 获取下拉框中的选项
     * @param userAndDepartmentGetDTO 获取用户的相关信息
     * @param dataList 数据列表
     * @param fieldAttrEntity 联动显示字段
     * @return
     * @throws XbbException
     */
    @Override
    public List<ItemDataPoJo> getItemDataList(UserAndDepartmentGetDTO userAndDepartmentGetDTO,
                                               List<PaasFormDataEntityExt> dataList, FieldAttrEntity fieldAttrEntity, Integer saasMark, Integer businessType, Long formId, FieldAttrEntity thisFieldAttrEntity) throws XbbException{
        List<ItemDataPoJo> list = new ArrayList<>();
        try {
            Map<String, UserEntity> userMap = userHelp.getUserMapByList(fieldAttrEntity, dataList, userAndDepartmentGetDTO.getCorpid(), true);
            Map<String, DepartmentEntity> departmentMap = userHelp.getDepartmentMapByList(fieldAttrEntity, dataList, userAndDepartmentGetDTO.getCorpid(), true);
            Integer fieldType = fieldAttrEntity.getFieldType();

            String linkField = fieldAttrEntity.getAttr();
            String corpid = userAndDepartmentGetDTO.getCorpid();
            for (PaasFormDataEntityExt paasFormDataEsEntity: dataList) {
                if (Objects.equals(FieldTypeEnum.SERIALNO.getType(), fieldType)) {
                    ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                    itemDataPoJo.setText(paasFormDataEsEntity.getSerialNo());
                    itemDataPoJo.setValue(paasFormDataEsEntity.getSerialNo());
                    list.add(itemDataPoJo);
                }
                JSONObject data = paasFormDataEsEntity.getData();
                if (Objects.isNull(data)) {
                    continue;
                }
                Iterator iterator = data.keySet().iterator();
                while (iterator.hasNext()){
                    String key = iterator.next().toString();
                    if(key.equals(linkField)){
                        ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                        if (Objects.isNull(data.get(key))) {
                            continue;
                        }
                        if(Objects.equals(FieldTypeEnum.DATETIME.getType(), fieldType)){
                            itemDataPoJo.setText(data.get(key));
                            itemDataPoJo.setValue(data.get(key));
                            list.add(itemDataPoJo);
                        }else if(Objects.equals(FieldTypeEnum.COMBO_CHECK.getType(), fieldType)
                                || Objects.equals(FieldTypeEnum.CHECKBOX_GROUP.getType(), fieldType)){
                            List<Object> arrayList = (List<Object>) data.get(key);
                            if (Objects.equals(ComboTypeEnum.CUSTOM.getType(), fieldAttrEntity.getComboType())) {
                                List<ItemPoJo> itemList = fieldAttrEntity.getItems();
                                Map<Object, ItemPoJo> itemMap = new HashMap<>(itemList.size());
                                itemList.forEach(item->{
                                    itemMap.put(item.getValue(), item);
                                });
                                for(Object object: arrayList) {
                                    if (Objects.isNull(itemMap.get(object))) {
                                        continue;
                                    }
                                    ItemDataPoJo itemData = new ItemDataPoJo();
                                    itemData.setText(itemMap.get(object).getText());
                                    itemData.setValue(itemMap.get(object).getText());
                                    list.add(itemData);
                                }
                            } else {
                                for(Object object: arrayList) {
                                    ItemDataPoJo itemData = new ItemDataPoJo();
                                    itemData.setText(object);
                                    itemData.setValue(object);
                                    list.add(itemData);
                                }
                            }
                        } else if(Objects.equals(FieldTypeEnum.COMBO.getType(), fieldType)
                                || Objects.equals(FieldTypeEnum.RADIO_GROUP.getType(), fieldType)){
                            Object value = data.get(key);
                            if (Objects.equals(ComboTypeEnum.CUSTOM.getType(), fieldAttrEntity.getComboType())) {
                                List<ItemPoJo> itemList = fieldAttrEntity.getItems();
                                // 不是子表单
                                if (Objects.equals(saasMark, SaasMarkEnum.SAAS.getCode()) && StringUtil.isEmpty(fieldAttrEntity.getParentAttr())) {
                                    itemList = proFormHelp.getItem(fieldAttrEntity, businessType, corpid, formId);
                                }
                                Map<Object, ItemPoJo> itemMap = new HashMap<>(itemList.size());
                                ItemPoJo isOtherItem = null;
                                boolean isOther = false;
                                for (ItemPoJo item : itemList) {
                                    itemMap.put(item.getValue().toString(), item);
                                    if (Objects.equals(1, item.getIsOther())) {
                                        isOtherItem = item;
                                        isOther = true;
                                    }
                                }
                                ItemPoJo itemPoJo = itemMap.get(value.toString());
                                if (Objects.isNull(itemPoJo) && !isOther) {
                                    continue;
                                } else if (Objects.isNull(itemPoJo) && isOther) {
                                    itemPoJo = isOtherItem;
                                }
                                itemDataPoJo.setIsOther(itemPoJo.getIsOther());

                                if (Objects.equals(1, itemPoJo.getIsOther())) {
                                    // 如果是个其他，用户自己填
                                    itemDataPoJo.setValue(value);
                                    itemDataPoJo.setText(value);
                                } else {
                                    String text = itemPoJo.getText();
                                    itemDataPoJo.setText(text);
                                    itemDataPoJo.setValue(text);
                                }
                                list.add(itemDataPoJo);
                            } else {
                                value = ItemUtil.getCustomItemList(fieldAttrEntity, data);
                                if (Objects.nonNull(value) && StringUtil.isNotEmpty(value.toString())) {
                                    itemDataPoJo.setText(value);
                                    itemDataPoJo.setValue(value);
                                    list.add(itemDataPoJo);
                                }
                            }
                        } else if (Objects.equals(FieldTypeEnum.USER.getType(), fieldType)
                                || Objects.equals(FieldTypeEnum.USER_GROUP.getType(), fieldType)) {
                            if(StringUtil.isNotEmpty(data.getString(key))){
                                Object value = data.get(key);
                                if (value instanceof List) {
                                    List<String> userList = JSONArray.parseArray(data.getString(key), String.class);
                                    if(CollectionsUtil.isNotEmpty(userList)){
                                        List<ReturnUserAndDepartmentPojo> userEntities = new ArrayList<>();
                                        for (String item: userList) {
                                            if (userMap.containsKey(item)) {
                                                UserEntity userEntity = userMap.get(item);
                                                ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                                                BeanUtil.copyProperties(userEntity, returnUserAndDepartmentPojo);
                                                returnUserAndDepartmentPojo.setId(userEntity.getUserId());
                                                userEntities.add(returnUserAndDepartmentPojo);
                                            }
                                        }
                                        itemDataPoJo.setText(userEntities);
                                        itemDataPoJo.setValue(userEntities);
                                        list.add(itemDataPoJo);
                                    }
                                } else if (userMap.containsKey(data.getString(key))){
                                    UserEntity userEntity = userMap.get(data.getString(key));
                                    ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                                    BeanUtil.copyProperties(userEntity, returnUserAndDepartmentPojo);
                                    returnUserAndDepartmentPojo.setId(userEntity.getUserId());
                                    itemDataPoJo.setValue(returnUserAndDepartmentPojo);
                                    itemDataPoJo.setText(returnUserAndDepartmentPojo);
                                    list.add(itemDataPoJo);
                                }
                            }
                        } else if (Objects.equals(FieldTypeEnum.LINK_DATA.getType(), fieldType) || Objects.equals(FieldTypeEnum.LINK_DATA_MULTI.getType(), fieldType)) {
                            String attr = fieldAttrEntity.getAttr();
                            LinkInfoPojo linkInfoPojo = fieldAttrEntity.getLinkInfo();
                            Integer linkSaasMark = linkInfoPojo.getLinkSaasMark();
                            Integer linkBusinessType = linkInfoPojo.getLinkBusinessType();
                            Long linkFormId = linkInfoPojo.getLinkFormId();
                            DefaultLinkInfoPojo defaultLinkInfoPojo = new DefaultLinkInfoPojo();
                            Object value = data.get(key);
                            if (value instanceof Number) {
                                Long linkDataId = Long.parseLong(value.toString());
                                defaultLinkInfoPojo.setDataId(linkDataId);
                            } else if (value instanceof List) {
                                List<Long> linkDataIdList = JSON.parseArray(JSON.toJSONString(value), Long.class);
                                defaultLinkInfoPojo.setDataId(linkDataIdList);
                            }
                            defaultLinkInfoPojo.setFormId(linkFormId);
                            defaultLinkInfoPojo.setSaasMark(linkSaasMark);
                            defaultLinkInfoPojo.setBusinessType(linkBusinessType);
                            LinkListPojo linkListPojo = new LinkListPojo();
                            linkListPojo.setLinkAppId(linkInfoPojo.getLinkAppId());
                            linkListPojo.setLinkFormId(linkFormId);
                            linkListPojo.setLinkMenuId(linkInfoPojo.getLinkMenuId());
                            linkListPojo.setLinkSaasMark(linkSaasMark);
                            linkListPojo.setLinkBusinessType(linkBusinessType);
                            linkListPojo.setAttr(attr);
                            defaultLinkInfoPojo.setLinkList(linkListPojo);
                            JSONArray linkDataResult = paasFormHelp.setRelyLinkData(userAndDepartmentGetDTO, defaultLinkInfoPojo, fieldAttrEntity, userMap, departmentMap);
                            if (CollectionUtils.isNotEmpty(linkDataResult)) {
                                if (Objects.nonNull(thisFieldAttrEntity) && Objects.equals(thisFieldAttrEntity.getFieldType(), FieldTypeEnum.LINK_DATA.getType())) {
                                    itemDataPoJo.setText(linkDataResult.getJSONObject(0));
                                    itemDataPoJo.setValue(linkDataResult.getJSONObject(0));
                                    list.add(itemDataPoJo);
                                } else {
                                    itemDataPoJo.setText(linkDataResult);
                                    itemDataPoJo.setValue(linkDataResult);
                                    list.add(itemDataPoJo);
                                }
                            }
                        } else if (Objects.equals(FieldTypeEnum.DEPT.getType(), fieldType) ||
                                Objects.equals(FieldTypeEnum.DEPT_GROUP.getType(), fieldType)) {
                            if(StringUtil.isNotEmpty(data.getString(key))){
                                Object value = data.get(key);
                                if (value instanceof List) {
                                    List<String> departmentList = JSONArray.parseArray(data.getString(key), String.class);
                                    if(CollectionsUtil.isNotEmpty(departmentList)){
                                        List<ReturnUserAndDepartmentPojo> departmentEntities = new ArrayList<>();
                                        for (String item: departmentList) {
                                            if (departmentMap.containsKey(item)) {
                                                DepartmentEntity departmentEntity = departmentMap.get(item);
                                                ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                                                BeanUtil.copyProperties(departmentEntity, returnUserAndDepartmentPojo);
                                                departmentEntities.add(returnUserAndDepartmentPojo);
                                            }
                                        }
                                        itemDataPoJo.setValue(departmentEntities);
                                        itemDataPoJo.setText(departmentEntities);
                                        list.add(itemDataPoJo);
                                    }
                                } else  if (departmentMap.containsKey(data.getString(key))) {
                                    DepartmentEntity departmentEntity = departmentMap.get(data.getString(key));
                                    ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                                    BeanUtil.copyProperties(departmentEntity, returnUserAndDepartmentPojo);
                                    itemDataPoJo.setValue(returnUserAndDepartmentPojo);
                                    itemDataPoJo.setText(returnUserAndDepartmentPojo);
                                    list.add(itemDataPoJo);
                                }
                            }
                        } else if (Objects.equals(FieldTypeEnum.NUM.getType(), fieldType)) {
                            Double value = data.getDouble(key);
                            itemDataPoJo.setText(value);
                            itemDataPoJo.setValue(value);
                            list.add(itemDataPoJo);

                        } else if (Objects.equals(FieldTypeEnum.STAGE_THRUSTER.getType(), fieldType)) {
                            Object value = data.get(key);
                            List<ItemPoJo> itemList =  proFormHelp.getEditStageComboItems(fieldAttrEntity, saasMark, businessType, corpid, formId, data);
                            Map<Object, ItemPoJo> itemMap = new HashMap<>(itemList.size());
                            for (ItemPoJo item : itemList) {
                                itemMap.put(item.getValue().toString(), item);
                            }
                            ItemPoJo itemPoJo = itemMap.get(value.toString());
                            if (Objects.isNull(itemPoJo)) {
                                continue;
                            }
                            itemDataPoJo.setIsOther(itemPoJo.getIsOther());
                            String text = itemPoJo.getText();
                            itemDataPoJo.setText(text);
                            itemDataPoJo.setValue(text);
                            list.add(itemDataPoJo);
                        } else{
                            itemDataPoJo.setText(data.get(key));
                            itemDataPoJo.setValue(data.get(key));
                            list.add(itemDataPoJo);
                        }
                    }
                }
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("DistinctDataServiceImpl.getItemDataList 出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return list;
    }

    /**
     * 产品只筛选父产品
     * @param boolQueryBuilder
     * @param businessType
     * @param subBusinessType
     * @param attr
     */
    @Override
    public void productCondition(BoolQueryBuilder boolQueryBuilder, Integer businessType, Integer subBusinessType, String attr) {
        ParentBusinessConditionUtil.productCondition(boolQueryBuilder, businessType, subBusinessType, attr);
    }

    /**
     * 下拉框的模糊搜索
     * @param conditionValue
     * @param fieldAttrEntity
     * @param corpid
     * @param formId
     * @param businessType
     * @param saasMark
     * @param boolQueryBuilder
     * @throws XbbException
     */
    @Override
    public void likeBoolQuery(Object conditionValue, FieldAttrEntity fieldAttrEntity, String corpid, Long formId,
                               Integer businessType, Integer saasMark, BoolQueryBuilder boolQueryBuilder) throws XbbException {
        if(conditionValue != null && StringUtil.isNotEmpty(conditionValue.toString())){
            String linkField = fieldAttrEntity.getAttr();
            FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(fieldAttrEntity.getFieldType());
            String name = "data."+linkField;
            switch (fieldTypeEnum) {
                case COMBO:
                case COMBO_CHECK:
                case RADIO_GROUP:
                case CHECKBOX_GROUP:
                    if (Objects.equals(ComboTypeEnum.CUSTOM.getType(), fieldAttrEntity.getComboType())) {
                        List<ItemPoJo> itemList = fieldAttrEntity.getItems();
                        if (Objects.equals(saasMark, SaasMarkEnum.SAAS.getCode())) {
                            itemList = proFormHelp.getItem(fieldAttrEntity, businessType, corpid, formId);
                        }
                        List<Object> valueList = new ArrayList<>();
                        itemList.forEach(item->{
                            if (item.getText().contains(conditionValue.toString())) {
                                valueList.add(item.getValue());
                            }
                        });

                        BoolQueryBuilder comboBool = boolQuery();
                        if (!valueList.isEmpty()) {
                            valueList.forEach(value->{
                                comboBool.should(termsQuery( name + StringConstant.POINT + StringConstant.KEY_WORD, value));
                            });
                        }
                        comboBool.minimumShouldMatch(EsNormalConstant.MINI_MUM_SHOULD_MATCH);
                        boolQueryBuilder.filter(comboBool);
                    } else {
                        QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(name, conditionValue);
                        boolQueryBuilder.filter(queryBuilder);
                    }
                    break;
                default:
                    QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(name, conditionValue);
                    boolQueryBuilder.filter(queryBuilder);
                    break;
            }

        }
    }

    @Override
    public SearchDataInConditionVO listOfLinkData(FieldAttrEntity fieldAttrEntity, SearchDataInConditionDTO searchDataInConditionDTO) throws XbbException {
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        try {
            String corpid = searchDataInConditionDTO.getCorpid();
            List<ItemDataPoJo> items = new ArrayList<>();
            LinkInfoPojo linkInfoPojo = fieldAttrEntity.getLinkInfo();
            PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(searchDataInConditionDTO.getCorpid(), linkInfoPojo.getLinkFormId(), linkInfoPojo.getLinkBusinessType());
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), linkInfoPojo.getLinkKey());
            FieldAttrEntity linkFieldEntity = explainMap.get(linkInfoPojo.getLinkKey());
            TransmittableThreadLocalUtil.setValue(linkInfoPojo.getLinkSaasMark(), linkInfoPojo.getLinkBusinessType(), linkInfoPojo.getLinkMenuId(), searchDataInConditionDTO.getDistributorMark());

            // 获取权限内的数据
            searchDataInConditionDTO.getConditionsList().clear();
            searchDataInConditionDTO.setBusinessType(linkInfoPojo.getLinkBusinessType());
            searchDataInConditionDTO.setSubBusinessType(linkInfoPojo.getLinkBusinessType());
            searchDataInConditionDTO.setFormId(linkInfoPojo.getLinkFormId());
            searchDataInConditionDTO.setSaasMark(linkInfoPojo.getLinkSaasMark());
            searchDataInConditionDTO.setDefaultGroup(1);
            searchDataInConditionDTO.setListGroupId(ListGroupEnum.ALL.getCode().longValue());
            saasListHelp.packageSearchDataCondition(searchDataInConditionDTO);
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            //解析查询条件
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("formId", searchDataInConditionDTO.getFormId()));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));

            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(searchDataInConditionDTO.getCorpid(), searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getSaasMark());

            // 关联数据筛选可以获取到客户/线索公海池的数据
            if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), searchDataInConditionDTO.getBusinessType())){
                searchDataInConditionDTO.getConditionsList().removeIf(e -> Objects.equals(e.getAttr(), CustomerManagementEnum.IS_PUBLIC.getAttr()));
            }else if (Objects.equals(XbbRefTypeEnum.CLUE.getCode(), searchDataInConditionDTO.getBusinessType())){
                searchDataInConditionDTO.getConditionsList().removeIf(e -> Objects.equals(e.getAttr(), ClueEnum.IS_PUBLIC.getAttr()));
            }

            EsUtil.parseCondition(boolQueryBuilder,searchDataInConditionDTO.getConditionsList(),"", corpid,searchDataInConditionDTO.getBusinessType());
            EsUtil.parseShouldCondition(boolQueryBuilder,searchDataInConditionDTO.getShouldConditionsList(),"", corpid,searchDataInConditionDTO.getBusinessType());
            // 共享权限
            EsUtil.parseSharePermissionCondition(boolQueryBuilder, searchDataInConditionDTO.getSharePermission(), corpid, searchDataInConditionDTO.getBusinessType(), false);

            productCondition(boolQueryBuilder,searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getSubBusinessType(), linkFieldEntity.getAttr());

            List<Object> valueList = searchDataInConditionDTO.getValueList();
            if (CollectionUtils.isNotEmpty(valueList)) {
                boolQueryBuilder.filter(termsQuery("dataId", valueList));

                if (Objects.equals(searchDataInConditionDTO.getFrom(), SearchDataFromEnum.SHARE_PERMISSION.getFrom())
                        && Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.PRODUCT.getCode())) {
                    boolQueryBuilder.filter().remove(termQuery("data." + ProductEnum.PARENT_ID.getAttr(), 0));
                    boolQueryBuilder.mustNot(termQuery("data." + ProductEnum.PARENT_ID.getAttr(),0));
                }
            }

            String attr = linkFieldEntity.getAttr();
            String field = "data." + attr;
            if (Objects.equals(FieldTypeEnum.SERIALNO.getAlias(), attr)) {
                field = attr;
            }
            String name = field + ".keyword";
            // 模糊查询 类似于sql中的like
            Object conditionValue = searchDataInConditionDTO.getValue();
            if (conditionValue != null && StringUtil.isNotEmpty(conditionValue.toString())) {
                QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(field, searchDataInConditionDTO.getValue());
                boolQueryBuilder.filter(queryBuilder);
            }
            boolQueryBuilder.filter(existsQuery(name.replace(".keyword", "")));
            boolQueryBuilder.mustNot(termQuery(name, ""));

            BoolQueryBuilder childBuilder = boolQuery();
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.query(boolQueryBuilder);
            // 设置join_field

            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, indexTypeEnum.getType()));
            // 排序
            sourceBuilder.sort(new FieldSortBuilder(FieldTypeEnum.UPDATETIME.getAlias()).order(SortOrder.DESC));
            if (Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), searchDataInConditionDTO.getBusinessType())) {
                List<String> parentFieldList = new ArrayList<>();
                parentFieldList.add(StringConstant.DATA_ID);
                boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_PRODUCT.getType()));
                List<PaasFormDataEntityExt> list = paasEsModel.list(sourceBuilder, IndexTypeEnum.IDX_SAAS_PRODUCT, parentFieldList, 1, 10);
                if (CollectionsUtil.isNotEmpty(list)) {
                    List<Long> dataIdList = list.stream().map(PaasFormDataEntityExt::getDataId).collect(Collectors.toList());
                    childBuilder.filter(termQuery("corpid.keyword", corpid));
                    childBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                    childBuilder.filter(termsQuery(StringConstant.JSON_DATA + StringConstant.POINT + ProductEnum.PARENT_ID.getAttr(), dataIdList));
                } else {
                    return searchDataInConditionVO;
                }
            }
            List<String> fieldSourceList = Arrays.asList(FieldTypeEnum.DATAID.getAlias(), attr);
            if (Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), searchDataInConditionDTO.getBusinessType())
                    && CollectionUtils.isEmpty(valueList)) {
                sourceBuilder.query(childBuilder);
                String specificationLinkAttr = ProductEnum.SPECIFICATION_LINK_TEXT.getAttr();
                String specificationAttr = ProductEnum.SPECIFICATION.getAttr();
                fieldSourceList = Arrays.asList(specificationLinkAttr, specificationAttr, attr);
            }
            // 获取es的index和type

            List<PaasFormDataEntityExt> dataList = paasEsModel.list(sourceBuilder, indexTypeEnum, fieldSourceList, 1, 10);
            if (dataList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }

            for (PaasFormDataEntityExt paasFormDataEntityExt : dataList) {
                ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                itemDataPoJo.setValue(paasFormDataEntityExt.getDataId());
                if (Objects.equals(FieldTypeEnum.SERIALNO.getAlias(), attr)) {
                    itemDataPoJo.setText(paasFormDataEntityExt.getSerialNo());
                } else {
                    JSONObject data = paasFormDataEntityExt.getData();
                    if (Objects.nonNull(data)) {
                        String text = data.getString(attr);
                        if (Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), searchDataInConditionDTO.getBusinessType())
                                && Objects.equals(attr, ProductEnum.NAME.getAttr()) && Objects.equals(1, data.get(ProductEnum.SPECIFICATION.getAttr()))) {
                            String specification = specificationModel.joinSpecification(data.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr()));
                            text = data.getString(attr) + "（" + specification + "）";
                        } else if (FieldTypeEnum.RADIO_GROUP.getType().equals(linkFieldEntity.getFieldType())
                                || FieldTypeEnum.COMBO.getType().equals(linkFieldEntity.getFieldType())) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put(attr, text);
                            JSONObject result = new JSONObject();
                            formDataAnalysisHelp.analysisCombo(jsonObject, result, linkFieldEntity, searchDataInConditionDTO.getCorpid());
                            if (StringUtil.isNotEmpty(result.getString(attr))) {
                                text = result.getString(attr);
                            }
                        }
                        itemDataPoJo.setText(text);
                    }
                }
                items.add(itemDataPoJo);
            }
            searchDataInConditionVO.setItems(items);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("DistinctDataServiceImpl.listOfLinkData 出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return searchDataInConditionVO;
    }


    @Override
    public SearchDataInConditionVO listOfBusiness(SearchDataInConditionDTO searchDataInConditionDTO) throws XbbException {
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        String corpid = searchDataInConditionDTO.getCorpid();
        Long formId = searchDataInConditionDTO.getFormId();
        Integer businessType = searchDataInConditionDTO.getBusinessType();
        Integer saasMark = searchDataInConditionDTO.getSaasMark();
        String attr = searchDataInConditionDTO.getAttr();
        String subAttr = searchDataInConditionDTO.getSubAttr();

        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, businessType, saasMark);

        BoolQueryBuilder boolQueryBuilder = boolQuery();
        //解析查询条件
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery("formId", formId));
        boolQueryBuilder.filter(termQuery("del", searchDataInConditionDTO.getDel()));
        String field = "data." + attr;
        if (StringUtils.isNotEmpty(subAttr)) {
            field = "data." + subAttr;
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.getSubEnum(indexTypeEnum).getType()));
        } else {
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, indexTypeEnum.getType()));
            saasListHelp.packageSearchDataCondition(searchDataInConditionDTO);
            EsUtil.parseCondition(boolQueryBuilder,searchDataInConditionDTO.getConditionsList(),"", corpid, businessType);
            // 共享权限
            EsUtil.parseSharePermissionCondition(boolQueryBuilder, searchDataInConditionDTO.getSharePermission(), corpid, businessType, false);
        }
        String name = field + ".keyword";
        boolQueryBuilder.filter(existsQuery(field));
        boolQueryBuilder.mustNot(termQuery(name, ""));

        try {

            Object conditionValue = searchDataInConditionDTO.getValue();
            if (Objects.nonNull(conditionValue) && StringUtils.isNotEmpty(conditionValue.toString())) {
                QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(field, searchDataInConditionDTO.getValue());
                boolQueryBuilder.filter(queryBuilder);
            }

            SearchRequest searchRequest = new SearchRequest();
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(boolQueryBuilder);
            TermsAggregationBuilder termsAggregation = AggregationBuilders.terms("aggs01").field(name).size(EsNormalConstant.TEN_NUM);
            termsAggregation.executionHint(ElasticConstant.EXECUTION_HINT);
            searchSourceBuilder.aggregation(termsAggregation).size(0);
            searchRequest.source(searchSourceBuilder);
            searchRequest.indices(indexTypeEnum.getIndex());
            JSONArray resultArray = xbbElasticsearchRestTemplate.getAggResponseJson(searchRequest).getJSONObject("aggregations").getJSONObject("aggs01").getJSONArray("buckets");
            List<ItemDataPoJo> items = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(resultArray)) {
                ItemDataPoJo itemDataPoJo;
                for (Object o : resultArray) {
                    JSONObject object = (JSONObject) o;
                    itemDataPoJo = new ItemDataPoJo();
                    itemDataPoJo.setText(object.getString(StringConstant.KEY));
                    itemDataPoJo.setValue(object.getString(StringConstant.KEY));
                    items.add(itemDataPoJo);
                }
            }
            searchDataInConditionVO.setItems(items);
            return searchDataInConditionVO;
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("DistinctDataServiceImpl.listOfBusiness 出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

    }

    @Override
    public SearchDataInConditionVO listOfLabel(FieldAttrEntity fieldAttrEntity, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) throws XbbException {
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        PaasFormEntity paasFormEntity = new PaasFormEntity();
        try {
            if (Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())) {
                //工单
                WorkOrderFormEntity workOrderFormEntity = workOrderFormModel.getByKey(searchDataInConditionDTO.getFormId(), searchDataInConditionDTO.getCorpid());
                BeanUtil.copyProperties(workOrderFormEntity, paasFormEntity);
            } else {
                paasFormEntity = paasFormModel.getByFormId(searchDataInConditionDTO.getFormId(),searchDataInConditionDTO.getCorpid());
            }
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", searchDataInConditionDTO.getCorpid());
            param.put("formId", searchDataInConditionDTO.getFormId());
            if (StringUtil.isNotEmpty(String.valueOf(searchDataInConditionDTO.getValue()))) {
                param.put("nameLike", searchDataInConditionDTO.getValue());
            }
            param.put("appId", paasFormEntity.getAppId());
            param.put("del", DelEnum.NORMAL.getDel());
            if (Objects.equals(searchDataInConditionDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
                param.put("start", 0);
                param.put("pageNum", 10);
            }
            List<LabelEntity> entitys = labelModel.findEntitys(param);
            List<ItemDataPoJo> items = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(entitys)) {
                ItemDataPoJo itemDataPoJo;
                for (LabelEntity labelEntity : entitys) {
                    itemDataPoJo = new ItemDataPoJo();
                    itemDataPoJo.setText(labelEntity.getName());
                    itemDataPoJo.setValue(labelEntity.getId());
                    items.add(itemDataPoJo);
                }
            }
            searchDataInConditionVO.setItems(items);
        } catch (Exception e) {
            LOG.error("获取标签失败",e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return searchDataInConditionVO;
    }

    @Override
    public SearchDataInConditionVO listOfScoreRange(FieldAttrEntity fieldAttrEntity, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) throws XbbException {
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        if(Objects.nonNull(fieldAttrEntity)){
            String corpid = searchDataInConditionDTO.getCorpid();
            Long formId = searchDataInConditionDTO.getFormId();
            if(FieldTypeEnum.SCORE_RANGE.equals(fieldTypeEnum)){
                List<ItemPoJo> items = scoreRangeService.getItems4ScoreRangeScreen(corpid, formId);
                if(CollectionsUtil.isNotEmpty(items)){
                    List<ItemDataPoJo> itemDatas = new ArrayList<>();
                    ItemDataPoJo itemDataPoJo;
                    for(ItemPoJo itemPoJo : items){
                        itemDataPoJo = new ItemDataPoJo();
                        BeanUtil.copyProperties(itemPoJo,itemDataPoJo);
                        itemDatas.add(itemDataPoJo);
                    }
                    searchDataInConditionVO.setItems(itemDatas);
                }
            }
        }
        return searchDataInConditionVO;
    }

    @Override
    public SearchDataInConditionVO listofStageInfo(SearchDataInConditionDTO searchDataInConditionDTO, FieldAttrEntity fieldAttrEntity) throws XbbException {
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        if(Objects.nonNull(fieldAttrEntity)){
            String corpid = searchDataInConditionDTO.getCorpid();
            Long formId = searchDataInConditionDTO.getFormId();
            List<ItemPoJo> items = proFormHelp.getEnableStageComboItems(searchDataInConditionDTO.getSaasMark(), searchDataInConditionDTO.getBusinessType(), corpid, formId);
                if(CollectionsUtil.isNotEmpty(items)){
                    List<ItemDataPoJo> itemDatas = new ArrayList<>();
                    ItemDataPoJo itemDataPoJo;
                    for(ItemPoJo itemPoJo : items){
                        itemDataPoJo = new ItemDataPoJo();
                        BeanUtil.copyProperties(itemPoJo,itemDataPoJo);
                        itemDatas.add(itemDataPoJo);
                    }
                    searchDataInConditionVO.setItems(itemDatas);
                }
            }
        return searchDataInConditionVO;
    }

    /**
     * 封装人员筛选选项
     * @param searchInConditionDTO
     * @return com.xbongbong.paas.pojo.vo.SearchDataInConditionVO
     * @throws XbbException
     * @author 吴峰、饶龙等
     * @since v1.0
     * @version v1.0
     * @update 2022.6.28 by zcp 封装人员筛选方法，内部逻辑未做任何改动
     */
    @Override
    public SearchDataInConditionVO listOfUser(SearchInConditionDTO searchInConditionDTO) throws XbbException {
        String corpid = searchInConditionDTO.getCorpid();
        Integer businessType = searchInConditionDTO.getBusinessType();
        List<ItemDataPoJo> itemList = new ArrayList<>();
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.equals(businessType, XbbRefTypeEnum.DATA_SET.getCode())) {
            //先过滤业务创建人
            List<String> userIdIn = dataSetModel.getCreatorIdList(corpid);
            if (CollectionUtils.isEmpty(userIdIn)) {
                //无创建人，则无需查询员工数据
                searchDataInConditionVO.setItems(itemList);
                return searchDataInConditionVO;
            }
            param.put("userIdIn", userIdIn);
        }
        List<UserEntity> userList;
        if (Objects.nonNull(searchInConditionDTO.getValue()) && StringUtil.isNotEmpty(searchInConditionDTO.getValue().toString())) {
            param.put("corpid", corpid);
            param.put("nameLike", searchInConditionDTO.getValue().toString());
            param.put(ParameterConstant.LEAVE_MARKS, BasicConstant.ONE);
            //param.put("del", 0);
            userList = userModel.findEntitys(param);
        } else if (CollectionUtils.isEmpty(searchInConditionDTO.getValueList())) {
            param.put("corpid", corpid);
            param.put("limitNum", 20);
            param.put(ParameterConstant.LEAVE_MARKS,BasicConstant.ONE);
            //param.put("del", 0);
            userList = userModel.findEntitys(param);
        } else {
            List<Object> valueList = searchInConditionDTO.getValueList();
            List<String> userIdIn = new ArrayList<>();
            valueList.forEach(item->{
                userIdIn.add(item.toString());
            });
            userList = userModel.getUserNamesByIdIn(corpid, userIdIn, BasicConstant.ONE);
        }
        if (CollectionUtils.isNotEmpty(userList)) {
            for (UserEntity userVO : userList) {
                ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                itemDataPoJo.setValue(userVO.getUserId());
                itemDataPoJo.setText(userVO.getName());
                itemList.add(itemDataPoJo);
            }
        }
        searchDataInConditionVO.setItems(itemList);
        return searchDataInConditionVO;
    }

    /**
     * 封装部门筛选选项
     * @param searchInConditionDTO
     * @return com.xbongbong.paas.pojo.vo.SearchDataInConditionVO
     * @throws XbbException
     * @author 吴峰
     * @version v1.0
     * @update 2022.6.28 by zcp 封装人员筛选方法，内部逻辑未做任何改动
     * @since v1.0
     */
    @Override
    public SearchDataInConditionVO listOfDepartment(SearchInConditionDTO searchInConditionDTO) throws XbbException {
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        DepartmentListDTO departmentListDTO = new DepartmentListDTO();
        BeanUtil.copyProperties(searchInConditionDTO, departmentListDTO);
        DepartmentListVO departmentListVO = departmentService.list(departmentListDTO);
        if (departmentListVO == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        searchDataInConditionVO.setDepartmentList(departmentListVO.getDepartmentTree());
        return searchDataInConditionVO;
    }

    @Override
    public SearchDataInConditionVO listOfProductEnable(FieldAttrEntity fieldAttrEntity, SearchDataInConditionDTO searchDataInConditionDTO, FieldTypeEnum fieldTypeEnum) {
        List<ItemDataPoJo> list = new ArrayList<>();
        list.add(new ItemDataPoJo(OperateTypeEnum.YES.getName(),"1"));
        list.add(new ItemDataPoJo(OperateTypeEnum.NO.getName(),"0"));
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        searchDataInConditionVO.setItems(DataUtil.filterRepetition(list));
        return searchDataInConditionVO;
    }
}
